WRITE(3)                   POSIX Programmer's Manual                  WRITE(3)



PPRROOLLOOGG
       This manual page is part of the POSIX Programmer's Manual.  The OS
       implementation of this interface may differ (consult the corresponding
       OS manual page for details of OS behavior), or the interface may not be
       implemented on OS.


NNAAMMEE
       pwrite, write -- write on a file

SSYYNNOOPPSSIISS
       #include <unistd.h>

       ssize_t pwrite(int _f_i_l_d_e_s, const void *_b_u_f, size_t _n_b_y_t_e,
           off_t _o_f_f_s_e_t);
       ssize_t write(int _f_i_l_d_e_s, const void *_b_u_f, size_t _n_b_y_t_e);

DDEESSCCRRIIPPTTIIOONN
       The _w_r_i_t_e() function shall attempt to write _n_b_y_t_e bytes from the buffer
       pointed to by _b_u_f to the file associated with the open file descriptor,
       _f_i_l_d_e_s.

       Before any action described below is taken, and if _n_b_y_t_e is zero and
       the file is a regular file, the _w_r_i_t_e() function may detect and return
       errors as described below. In the absence of errors, or if error
       detection is not performed, the _w_r_i_t_e() function shall return zero and
       have no other results. If _n_b_y_t_e 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 _f_i_l_d_e_s.  Before successful return from
       _w_r_i_t_e(), the file offset shall be incremented by the number of bytes
       actually written. On a regular file, if the position of the last byte
       written is greater than or equal 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 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 _w_r_i_t_e() requests that more bytes be written than there is room for
       (for example, the file size limit of the process 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 _w_r_i_t_e() is interrupted by a signal before it writes any data, it
       shall return -1 with _e_r_r_n_o set to [[EEIINNTTRR]].

       If _w_r_i_t_e() is interrupted by a signal after it successfully writes some
       data, it shall return the number of bytes written.

       If the value of _n_b_y_t_e is greater than {SSIZE_MAX}, the result is
       implementation-defined.

       After a _w_r_i_t_e() to a regular file has successfully returned:

        *  Any successful _r_e_a_d() from each byte position in the file that was
           modified by that write shall return the data specified by the
           _w_r_i_t_e() for that position until such byte positions are again
           modified.

        *  Any subsequent successful _w_r_i_t_e() 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 _n_b_y_t_e.

        *  If the O_NONBLOCK flag is set, _w_r_i_t_e() requests shall be handled
           differently, in the following ways:

           --  The _w_r_i_t_e() 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, _w_r_i_t_e() shall transfer all the data and return the number
               of bytes requested.  Otherwise, _w_r_i_t_e() shall transfer no data
               and return -1 with _e_r_r_n_o set to [[EEAAGGAAIINN]].

           --  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 _e_r_r_n_o set to [[EEAAGGAAIINN]].

       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, _w_r_i_t_e() shall block the calling
           thread until the data can be accepted.

        *  If the O_NONBLOCK flag is set, _w_r_i_t_e() shall not block the thread.
           If some data can be written without blocking the thread, _w_r_i_t_e()
           shall write what it can and return the number of bytes written.
           Otherwise, it shall return -1 and set _e_r_r_n_o to [[EEAAGGAAIINN]].

       Upon successful completion, where _n_b_y_t_e is greater than 0, _w_r_i_t_e()
       shall mark for update the last data modification and last file status
       change timestamps 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 _f_i_l_d_e_s.

       If _f_i_l_d_e_s refers to a socket, _w_r_i_t_e() shall be equivalent to _s_e_n_d()
       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 _f_i_l_d_e_s refers to a shared memory object, the result of the _w_r_i_t_e()
       function is unspecified.

       If _f_i_l_d_e_s refers to a typed memory object, the result of the _w_r_i_t_e()
       function is unspecified.

       If _f_i_l_d_e_s refers to a STREAM, the operation of _w_r_i_t_e() shall be
       determined by the values of the minimum and maximum _n_b_y_t_e range (packet
       size) accepted by the STREAM. These values are determined by the
       topmost STREAM module. If _n_b_y_t_e falls within the packet size range,
       _n_b_y_t_e bytes shall be written. If _n_b_y_t_e does not fall within the range
       and the minimum packet size value is 0, _w_r_i_t_e() 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
       _n_b_y_t_e does not fall within the range and the minimum value is non-zero,
       _w_r_i_t_e() shall fail with _e_r_r_n_o set to [[EERRAANNGGEE]].  Writing a zero-length
       buffer (_n_b_y_t_e 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
       _i_o_c_t_l() 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), _w_r_i_t_e() shall block until data can be accepted.

        *  If O_NONBLOCK is set and the STREAM cannot accept data, _w_r_i_t_e()
           shall return -1 and set _e_r_r_n_o to [[EEAAGGAAIINN]].

        *  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, _w_r_i_t_e() shall terminate and return the number of bytes
           written.

       In addition, _w_r_i_t_e() shall fail if the STREAM head has processed an
       asynchronous error before the call. In this case, the value of _e_r_r_n_o
       does not reflect the result of _w_r_i_t_e(), but reflects the prior error.

       The _p_w_r_i_t_e() function shall be equivalent to _w_r_i_t_e(), except that it
       writes into a given position and does not change the file offset
       (regardless of whether O_APPEND is set). The first three arguments to
       _p_w_r_i_t_e() are the same as _w_r_i_t_e() with the addition of a fourth argument
       _o_f_f_s_e_t for the desired position inside the file. An attempt to perform
       a _p_w_r_i_t_e() on a file that is incapable of seeking shall result in an
       error.

RREETTUURRNN VVAALLUUEE
       Upon successful completion, these functions shall return the number of
       bytes actually written to the file associated with _f_i_l_d_e_s.  This number
       shall never be greater than _n_b_y_t_e.  Otherwise, -1 shall be returned and
       _e_r_r_n_o set to indicate the error.

EERRRROORRSS
       These functions shall fail if:

       EEAAGGAAIINN 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 _w_r_i_t_e() operation.

       EEBBAADDFF  The _f_i_l_d_e_s argument is not a valid file descriptor open for
              writing.

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

       EEFFBBIIGG  The file is a regular file, _n_b_y_t_e 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 _f_i_l_d_e_s.

       EEIINNTTRR  The write operation was terminated due to the receipt of a
              signal, and no data was transferred.

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

       EENNOOSSPPCC There was no free space remaining on the device containing the
              file.

       EERRAANNGGEE The transfer request size was outside the range supported by the
              STREAMS file associated with _f_i_l_d_e_s.

       The _p_w_r_i_t_e() function shall fail if:

       EEIINNVVAALL The file is a regular file or block special file, and the _o_f_f_s_e_t
              argument is negative. The file pointer shall remain unchanged.

       EESSPPIIPPEE The file is a pipe, FIFO, or socket.

       The _w_r_i_t_e() function shall fail if:

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

       EEAAGGAAIINN or EEWWOOUULLDDBBLLOOCCKK
              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.

       EECCOONNNNRREESSEETT
              A write was attempted on a socket that is not connected.

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

       EEPPIIPPEE  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:

       EEIINNVVAALL The STREAM or multiplexer referenced by _f_i_l_d_e_s is linked
              (directly or indirectly) downstream from a multiplexer.

       EEIIOO    A physical I/O error has occurred.

       EENNOOBBUUFFSS
              Insufficient resources were available in the system to perform
              the operation.

       EENNXXIIOO  A request was made of a nonexistent device, or the request was
              outside the capabilities of the device.

       EENNXXIIOO  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, _e_r_r_n_o is set to the value
       included in the error message.

       The _w_r_i_t_e() function may fail if:

       EEAACCCCEESS A write was attempted on a socket and the calling process does
              not have appropriate privileges.

       EENNEETTDDOOWWNN
              A write was attempted on a socket and the local network
              interface used to reach the destination is down.

       EENNEETTUUNNRREEAACCHH
              A write was attempted on a socket and no route to the network is
              present.

       _T_h_e _f_o_l_l_o_w_i_n_g _s_e_c_t_i_o_n_s _a_r_e _i_n_f_o_r_m_a_t_i_v_e_.

EEXXAAMMPPLLEESS
   WWrriittiinngg ffrroomm aa BBuuffffeerr
       The following example writes data from the buffer pointed to by _b_u_f to
       the file associated with the file descriptor _f_d.

           ##iinncclluuddee <<ssyyss//ttyyppeess..hh>>
           ##iinncclluuddee <<ssttrriinngg..hh>>
           ......
           cchhaarr bbuuff[[2200]];;
           ssiizzee__tt nnbbyytteess;;
           ssssiizzee__tt bbyytteess__wwrriitttteenn;;
           iinntt ffdd;;
           ......
           ssttrrccppyy((bbuuff,, ""TThhiiss iiss aa tteesstt\\nn""));;
           nnbbyytteess == ssttrrlleenn((bbuuff));;

           bytes_written = write(fd, buf, nbytes);
           ...

AAPPPPLLIICCAATTIIOONN UUSSAAGGEE
       None.

RRAATTIIOONNAALLEE
       See also the RATIONALE section in _r_e_a_d().

       An attempt to write to a pipe or FIFO has several major
       characteristics:

        *  _A_t_o_m_i_c_/_n_o_n_-_a_t_o_m_i_c: 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 POSIX.1-2008 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.

        *  _B_l_o_c_k_i_n_g_/_i_m_m_e_d_i_a_t_e: 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; 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.

        *  _C_o_m_p_l_e_t_e_/_p_a_r_t_i_a_l_/_d_e_f_e_r_r_e_d: A write request:

               iinntt ffiillddeess;;
               ssiizzee__tt nnbbyyttee;;
               ssssiizzee__tt rreett;;
               cchhaarr **bbuuff;;

               ret = write(fildes, buf, nbyte);

           may return:

           Complete  _r_e_t=_n_b_y_t_e

           Partial   _r_e_t<_n_b_y_t_e

                     This shall never happen if _n_b_y_t_e<={PIPE_BUF}.  If it does
                     happen (with _n_b_y_t_e>{PIPE_BUF}), this volume of
                     POSIX.1-2008 does not guarantee atomicity, even if
                     _r_e_t<={PIPE_BUF}, because atomicity is guaranteed
                     according to the amount _r_e_q_u_e_s_t_e_d, not the amount
                     _w_r_i_t_t_e_n.

           Deferred: _r_e_t=-1, _e_r_r_n_o=[EAGAIN]

                     This error indicates that a later request may succeed. It
                     does not indicate that it _s_h_a_l_l succeed, even if
                     _n_b_y_t_e<={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 [[EEAAGGAAIINN]] is
                     caused by a particular value of _n_b_y_t_e>{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:

       +-----------------------------------------------------------------------+
       |            WWrriittee ttoo aa PPiippee oorr FFIIFFOO wwiitthh OO__NNOONNBBLLOOCCKK _c_l_e_a_r              |
       +---------------------+-------------------------------------------------+
       |IImmmmeeddiiaatteellyy WWrriittaabbllee::|     NNoonnee            SSoommee            _n_b_y_t_e       |
       +---------------------+-------------------------------------------------+
       |_n_b_y_t_e<={PIPE_BUF}    |Atomic blocking Atomic blocking Atomic immediate |
       |                     |_n_b_y_t_e           _n_b_y_t_e           _n_b_y_t_e            |
       +---------------------+-------------------------------------------------+
       |_n_b_y_t_e>{PIPE_BUF}     |Blocking _n_b_y_t_e  Blocking _n_b_y_t_e  Blocking _n_b_y_t_e   |
       +---------------------+-------------------------------------------------+
       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 _f_c_n_t_l()), a write request shall never block.

          +----------------------------------------------------------------+
          |          WWrriittee ttoo aa PPiippee oorr FFIIFFOO wwiitthh OO__NNOONNBBLLOOCCKK _s_e_t           |
          +---------------------+------------------------------------------+
          |IImmmmeeddiiaatteellyy WWrriittaabbllee::|    NNoonnee         SSoommee          _n_b_y_t_e      |
          +---------------------+------------------------------------------+
          |_n_b_y_t_e<={PIPE_BUF}    |-1, [EAGAIN] -1, [EAGAIN]  Atomic _n_b_y_t_e   |
          +---------------------+------------------------------------------+
          |_n_b_y_t_e>{PIPE_BUF}     |-1, [EAGAIN] <_n_b_y_t_e or -1, <=_n_b_y_t_e 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-2008 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 POSIX.1-2008 requires -1 to be returned and _e_r_r_n_o
       set to [[EEAAGGAAIINN]], 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-2008). The error
       indications in this volume of POSIX.1-2008 were chosen so that an
       application can distinguish these cases from end-of-file. While _w_r_i_t_e()
       cannot receive an indication of end-of-file, _r_e_a_d() 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 _w_r_i_t_e() indicates a successful write of an
       end-of-file indication.

       Implementations are allowed, but not required, to perform error
       checking for _w_r_i_t_e() 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 _r_e_a_d().

       Writes can be serialized with respect to other reads and writes. If a
       _r_e_a_d() of file data can be proven (by any means) to occur after a
       _w_r_i_t_e() of the data, it must reflect that _w_r_i_t_e(), 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 _w_r_i_t_e() calls to subsequent
       _r_e_a_d() 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 _r_e_a_d() and _w_r_i_t_e().  The XSI
       extensions _r_e_a_d_v() and _w_r_i_t_e_v() 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-2008 is also silent about any effects of
       application-level caching (such as that done by _s_t_d_i_o).

       This volume of POSIX.1-2008 does not specify the value of the file
       offset after an error is returned; there are too many cases. For
       programming errors, such as [[EEBBAADDFF]], the concept is meaningless since
       no file is involved. For errors that are detected immediately, such as
       [[EEAAGGAAIINN]], 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-2008 does not specify behavior of concurrent
       writes to a file from multiple processes. Applications should use some
       form of concurrency control.

       This volume of POSIX.1-2008 intentionally does not specify any _p_w_r_i_t_e()
       errors related to pipes, FIFOs, and sockets other than [[EESSPPIIPPEE]].

FFUUTTUURREE DDIIRREECCTTIIOONNSS
       None.

SSEEEE AALLSSOO
       _c_h_m_o_d(), _c_r_e_a_t(), _d_u_p(), _f_c_n_t_l(), _g_e_t_r_l_i_m_i_t(), _l_s_e_e_k(), _o_p_e_n(), _p_i_p_e(),
       _r_e_a_d(), _u_l_i_m_i_t(), _w_r_i_t_e_v()

       The Base Definitions volume of POSIX.1-2008, <<lliimmiittss..hh>>, <<ssttrrooppttss..hh>>,
       <<ssyyss__uuiioo..hh>>, <<uunniissttdd..hh>>

CCOOPPYYRRIIGGHHTT
       Portions of this text are reprinted and reproduced in electronic form
       from IEEE Std 1003.1, 2013 Edition, Standard for Information Technology
       -- Portable Operating System Interface (POSIX), The Open Group Base
       Specifications Issue 7, Copyright (C) 2013 by the Institute of
       Electrical and Electronics Engineers, Inc and The Open Group.  (This is
       POSIX.1-2008 with the 2013 Technical Corrigendum 1 applied.) In the
       event of any discrepancy between this version and the original IEEE and
       The Open Group Standard, the original IEEE and The Open Group Standard
       is the referee document. The original Standard can be obtained online
       at http://www.unix.org/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 .



IEEE/The Open Group                  2013                             WRITE(3)
