WRITE(3P)

okay bestie, you're reading the POSIX Programmer's Manual page for WRITE(3P)! it's all about pwrite and write, and honestly? it's a whole vibe. πŸ’–

✨ PROLOG ✨

so this manual page is part of the POSIX Programmer's Manual. heads up though: the Linux implementation of this interface may differ (consult the corresponding Linux manual page for the tea on Linux behavior), or the interface might not be implemented on Linux at all. πŸ’€

πŸŽ€ 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 πŸ’–

so write() is gonna try to write nbyte bytes from the buffer that buf points at, into the file that's linked to the open file descriptor fildes. πŸ’…

before anything else happens, if nbyte is zero and the file is a regular file, write() may detect and return errors as described below. if there are no errors, or if error detection isn't performed, write() has to return zero and do literally nothing else. but if nbyte is zero and the file is not a regular file? bestie, the results are unspecified 😭.

on a regular file (or any other file that can seek), the actual writing starts at the position in the file given by the file offset associated with fildes. before write() successfully returns, that file offset gets incremented by the number of bytes actually written. and on a regular file, if the position of the last byte written is greater than or equal to the file length, the file length gets set to that position plus one. slay. ✨

on a file that can't seek? writing always happens starting at the current position. the value of a file offset for that kind of device is undefined. πŸ’€

if the O_APPEND flag in the file status flags is set, then the file offset gets set to the end of the file before every write, and no other file modification operation can sneak in between changing the file offset and doing the write. no cap. πŸ”₯

if write() asks for more bytes than there's room for (like, the process's file size limit, or the physical end of a medium), then only as many bytes as there's room for get written. for example, say there's space for 20 more bytes in a file before hitting 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 push the file size past the process's soft file size limit, and there's no room for even one byte, the request fails and the implementation has to generate the SIGXFSZ signal for the thread. ⚠️

if write() gets interrupted by a signal before it writes any data, it returns -1 with errno set to [EINTR]. 😀

if write() gets interrupted by a signal after it's already successfully written some data, it returns the number of bytes written. periodt. πŸ’…

if nbyte is greater than {SSIZE_MAX}, the result is implementation-defined. yikes.

after a write() to a regular file has successfully returned, here's the tea:

  • any successful read() from each byte position in the file that was modified by that write has to return the data specified by the write() for that position, until those byte positions get modified again. πŸ’–
  • any later successful write() to the same byte position in the file overwrites that file data. simple as that. πŸ¦‹

write requests to a pipe or FIFO are handled the same way as a regular file, with these exceptions bestie:

  • there's no file offset for a pipe, so every write request appends to the end of the pipe. 🌈
  • write requests of {PIPE_BUF} bytes or less are not interleaved with data from other processes writing to the same pipe. writes greater than {PIPE_BUF} bytes may have data interleaved, on arbitrary boundaries, with writes from other processes β€” and that's true whether or not the O_NONBLOCK flag in 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 has to return nbyte. 😴
  • if the O_NONBLOCK flag is set, write() requests get handled differently, like this:
    • write() does not block the thread. 🚫
    • a write request for {PIPE_BUF} or fewer bytes has this effect: if there's enough space in the pipe, write() transfers all the data and returns the number of bytes requested. otherwise, write() transfers no data and returns -1 with errno set to [EAGAIN]. 😭
    • a write request for more than {PIPE_BUF} bytes causes one of these:
      • 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 has been read, it has to transfer at least {PIPE_BUF} bytes. ✨
      • when no data can be written, transfer no data, and return -1 with errno set to [EAGAIN]. πŸ’€

when you're trying to write to a file descriptor (that's not a pipe or FIFO) that supports non-blocking writes and can't take the data right away:

  • if the O_NONBLOCK flag is clear, write() blocks the calling thread until the data can be accepted. 😴
  • if the O_NONBLOCK flag is set, write() does not block the thread. if some data can be written without blocking, write() writes what it can and returns the number of bytes written. otherwise, it returns -1 and sets errno to [EAGAIN]. 🫢

on successful completion, if nbyte is greater than 0, write() marks the file's last data modification and last file status change timestamps for update, and if it's a regular file, the S_ISUID and S_ISGID bits of the file mode may be cleared. πŸ’…

for regular files, no data transfer happens past the offset maximum set in the open file description associated with fildes. 🚫

if fildes refers to a socket, write() is equivalent to send() with no flags set. πŸ”Œ

if the O_DSYNC bit is set, write I/O operations on the file descriptor complete as defined by synchronized I/O data integrity completion. ✨

if the O_SYNC bit is set, write I/O operations on the file descriptor complete as defined by synchronized I/O file integrity completion. 🌟

if fildes refers to a shared memory object, the result of write() is unspecified. 😭

if fildes refers to a typed memory object, the result of write() is unspecified. πŸ’€

if fildes refers to a STREAM, what write() does is determined by the minimum and maximum nbyte range (packet size) that the STREAM accepts. those values are set by the topmost STREAM module. if nbyte falls inside the packet size range, nbyte bytes get written. if nbyte doesn't fall in the range and the minimum packet size value is 0, write() breaks the buffer into maximum packet size segments before sending the data downstream (the last segment may have less than the maximum packet size). if nbyte doesn't fall in the range and the minimum value is non-zero, write() fails with errno set to [ERANGE]. writing a zero-length buffer (nbyte is 0) to a STREAMS device sends 0 bytes with 0 returned. but writing a zero-length buffer to a STREAMS-based pipe or FIFO sends no message and 0 is returned. the process may issue the I_SWROPT ioctl() to enable zero-length messages to be sent across the pipe or FIFO. 🌊

when writing to a STREAM, data messages get created with a priority band of 0. when writing to a STREAM that's not a pipe or FIFO:

  • if O_NONBLOCK is clear, and the STREAM can't accept data (the STREAM write queue is full because of internal flow control conditions), write() blocks until data can be accepted. 😴
  • if O_NONBLOCK is set and the STREAM can't accept data, write() returns -1 and sets errno to [EAGAIN]. πŸ’€
  • if O_NONBLOCK is set and part of the buffer has been written while a condition where the STREAM can't accept more data happens, write() terminates and returns the number of bytes written. ✨

also, write() fails if the STREAM head has processed an asynchronous error before the call. in that case, errno does not reflect the result of write() β€” it reflects the prior error. 😀

pwrite() is equivalent to write(), except it writes into a given position and does not change the file offset (no matter whether O_APPEND is set). the first three arguments to pwrite() are the same as write(), plus a fourth argument offset for the desired position inside the file. and trying to do a pwrite() on a file that can't seek results in an error. periodt. πŸ’…

πŸŽ€ RETURN VALUE πŸŽ€

on successful completion, these functions return the number of bytes actually written to the file associated with fildes. that number is never greater than nbyte. otherwise, -1 gets returned and errno is set to indicate the error. πŸŽ€

πŸ’₯ ERRORS πŸ’₯

okay bestie, error time. buckle up. 🎒

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 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 file size limit of the process, 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 calling thread is not blocking SIGTTOU, the process is not ignoring 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.
  • ERANGE β€” The transfer request size was outside the range supported by the STREAMS file associated with fildes.

The pwrite() function shall fail if:

  • EINVAL β€” The file is a regular file or block special file, and the offset argument is negative. The file offset shall remain unchanged.
  • ESPIPE β€” The file is incapable of seeking.

The write() 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 write operation.
  • 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 write operation.
  • 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. A SIGPIPE 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 socket is of type SOCK_STREAM, a SIGPIPE signal shall also be sent to the thread.

These 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 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.

okay bestie we're in the deep-lore part now πŸ’œ this is the RATIONALE β€” the "why is it Like That" section. buckle up, it's giving ✨ systems design ✨.


🌸 RATIONALE 🌸

See also the RATIONALE section in read(). (they're besties, the two rationales hold hands.)

So. An attempt to write to a pipe or FIFO has several major characteristics, and you gotta know all of them:

  • 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 lowkey iconic when you've got 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 POSIX.1‐2017 does not say whether write requests for more than {PIPE_BUF} bytes are atomic, but it requires that writes of {PIPE_BUF} or fewer bytes shall be atomic. no cap. πŸ”₯
  • 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 calling thread may block β€” like, 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. it's giving ✨chaos✨.
  • 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</marquee> β€” ret<nbyte

This shall never happen if nbyte≀{PIPE_BUF}. If it does happen (with nbyte>{PIPE_BUF}), this volume of POSIX.1‐2017 does not guarantee atomicity, even if ret≀{PIPE_BUF}, because atomicity is guaranteed according to the amount requested, not the amount written. read that again bestie, it's important. 😭

  • 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. that's the strategy, that's the play. 🧚

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 POSIX.1‐2017 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. forewarned is forearmed, babe. πŸ’ͺ

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. ✨progress✨

Where this volume of POSIX.1‐2017 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 POSIX.1‐2017). The error indications in this volume of POSIX.1‐2017 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. πŸ’€ sneaky.

Implementations are allowed, but not required, to perform error checking for write() requests of zero bytes. (so like, don't rely on it, bestie.)

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. rip {PIPE_MAX}, you would've hated it here πŸ•ŠοΈ

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. 😀 (yes, network filesystems, we're looking at you.)

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 POSIX.1‐2017 is also silent about any effects of application-level caching (such as that done by stdio). πŸ¦‹

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 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 POSIX.1‐2017 does not specify the behavior of concurrent writes to a regular file from multiple threads, except that each write is atomic (see Section 2.9.7, Thread Interactions with Regular File Operations). Applications should use some form of concurrency control. fr fr, use a lock, don't rawdog concurrent writes. πŸ”’

This volume of POSIX.1‐2017 intentionally does not specify any pwrite() errors related to pipes, FIFOs, and sockets other than [ESPIPE]. it's giving deliberately vague πŸ’…


🌈 FUTURE DIRECTIONS 🌈

None. πŸ’€ that's it. that's the future. nothing.


πŸ‘€ SEE ALSO πŸ‘€

  • chmod()
  • creat()
  • dup()
  • fcntl()
  • getrlimit()
  • lseek()
  • open()
  • pipe()
  • read()
  • ulimit()
  • writev()

The Base Definitions volume of POSIX.1‐2017, <limits.h>, <stropts.h>, <sys_uio.h>, <unistd.h>


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

Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .


and that's the whole page bestie!! πŸŽ€ go forth and write() responsibly, handle your partial writes, respect {PIPE_BUF}, and never ever trust a networked filesystem's caching. mwah πŸ’–

this absolute banger of a page came from IEEE/The Open Group, dated 2017, and it lives under the name WRITE(3P). πŸ¦‹βœ¨

πŸ“¦ where this page comes from