1WRITE(3P)                  POSIX Programmer's Manual                 WRITE(3P)
2
3
4

PROLOG

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

NAME

12       pwrite, write — write on a file
13

SYNOPSIS

15       #include <unistd.h>
16
17       ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
18           off_t offset);
19       ssize_t write(int fildes, const void *buf, size_t nbyte);
20

DESCRIPTION

22       The write() function shall attempt to write nbyte bytes from the buffer
23       pointed to by buf to the file associated with the open file descriptor,
24       fildes.
25
26       Before any action described below is taken, and if nbyte  is  zero  and
27       the  file is a regular file, the write() function may detect and return
28       errors as described below. In the absence of errors, or if error detec‐
29       tion  is not performed, the write() function shall return zero and have
30       no other results. If nbyte is zero and the file is not a regular  file,
31       the results are unspecified.
32
33       On  a regular file or other file capable of seeking, the actual writing
34       of data shall proceed from the position in the file  indicated  by  the
35       file  offset  associated  with  fildes.   Before successful return from
36       write(), the file offset shall be incremented by the  number  of  bytes
37       actually  written.  On a regular file, if the position of the last byte
38       written is greater than or equal to the length of the file, the  length
39       of the file shall be set to this position plus one.
40
41       On  a  file  not  capable  of  seeking, writing shall always take place
42       starting at the current position. The value of a file offset associated
43       with such a device is undefined.
44
45       If  the  O_APPEND flag of the file status flags is set, the file offset
46       shall be set to the end of the file prior to each write and  no  inter‐
47       vening  file  modification  operation  shall occur between changing the
48       file offset and the write operation.
49
50       If a write() requests that more bytes be written than there is room for
51       (for example, the file size limit of the process or the physical end of
52       a medium), only as many bytes as there is room for  shall  be  written.
53       For  example, suppose there is space for 20 bytes more in a file before
54       reaching a limit. A write of 512 bytes will return 20. The  next  write
55       of  a  non-zero  number of bytes would give a failure return (except as
56       noted below).
57
58       If the request would cause the file size to exceed the soft  file  size
59       limit for the process and there is no room for any bytes to be written,
60       the request shall  fail  and  the  implementation  shall  generate  the
61       SIGXFSZ signal for the thread.
62
63       If  write()  is  interrupted  by a signal before it writes any data, it
64       shall return -1 with errno set to [EINTR].
65
66       If write() is interrupted by a signal after it successfully writes some
67       data, it shall return the number of bytes written.
68
69       If the value of nbyte is greater than {SSIZE_MAX}, the result is imple‐
70       mentation-defined.
71
72       After a write() to a regular file has successfully returned:
73
74        *  Any successful read() from each byte position in the file that  was
75           modified  by  that  write  shall  return  the data specified by the
76           write() for that position until such byte positions are again modi‐
77           fied.
78
79        *  Any  subsequent successful write() to the same byte position in the
80           file shall overwrite that file data.
81
82       Write requests to a pipe or FIFO shall be handled in the same way as  a
83       regular file with the following exceptions:
84
85        *  There  is  no  file offset associated with a pipe, hence each write
86           request shall append to the end of the pipe.
87
88        *  Write requests of {PIPE_BUF} bytes or less shall not be interleaved
89           with  data  from  other  processes  doing  writes on the same pipe.
90           Writes of greater than {PIPE_BUF} bytes may have data  interleaved,
91           on arbitrary boundaries, with writes by other processes, whether or
92           not the O_NONBLOCK flag of the file status flags is set.
93
94        *  If the O_NONBLOCK flag is clear, a  write  request  may  cause  the
95           thread to block, but on normal completion it shall return nbyte.
96
97        *  If  the  O_NONBLOCK  flag is set, write() requests shall be handled
98           differently, in the following ways:
99
100           --  The write() function shall not block the thread.
101
102           --  A write request for {PIPE_BUF} or fewer bytes  shall  have  the
103               following effect: if there is sufficient space available in the
104               pipe, write() shall transfer all the data and return the number
105               of  bytes requested.  Otherwise, write() shall transfer no data
106               and return -1 with errno set to [EAGAIN].
107
108           --  A write request for more than {PIPE_BUF} bytes shall cause  one
109               of the following:
110
111               --  When at least one byte can be written, transfer what it can
112                   and return the number of bytes written. When all data  pre‐
113                   viously  written  to the pipe is read, it shall transfer at
114                   least {PIPE_BUF} bytes.
115
116               --  When no data can be written, transfer no data,  and  return
117                   -1 with errno set to [EAGAIN].
118
119       When  attempting  to  write  to a file descriptor (other than a pipe or
120       FIFO) that supports non-blocking writes  and  cannot  accept  the  data
121       immediately:
122
123        *  If  the  O_NONBLOCK  flag is clear, write() shall block the calling
124           thread until the data can be accepted.
125
126        *  If the O_NONBLOCK flag is set, write() shall not block the  thread.
127           If  some  data  can be written without blocking the thread, write()
128           shall write what it can and return the  number  of  bytes  written.
129           Otherwise, it shall return -1 and set errno to [EAGAIN].
130
131       Upon  successful  completion,  where  nbyte  is greater than 0, write()
132       shall mark for update the last data modification and last  file  status
133       change  timestamps  of the file, and if the file is a regular file, the
134       S_ISUID and S_ISGID bits of the file mode may be cleared.
135
136       For regular files, no data transfer shall occur past the offset maximum
137       established in the open file description associated with fildes.
138
139       If  fildes  refers  to  a socket, write() shall be equivalent to send()
140       with no flags set.
141
142       If the O_DSYNC bit has been set,  write  I/O  operations  on  the  file
143       descriptor shall complete as defined by synchronized I/O data integrity
144       completion.
145
146       If the O_SYNC bit has been  set,  write  I/O  operations  on  the  file
147       descriptor shall complete as defined by synchronized I/O file integrity
148       completion.
149
150       If fildes refers to a shared memory object, the result of  the  write()
151       function is unspecified.
152
153       If  fildes  refers  to a typed memory object, the result of the write()
154       function is unspecified.
155
156       If fildes refers to a STREAM, the operation of write() shall be  deter‐
157       mined  by  the  values  of  the minimum and maximum nbyte range (packet
158       size) accepted by the STREAM. These values are determined by  the  top‐
159       most  STREAM module. If nbyte falls within the packet size range, nbyte
160       bytes shall be written. If nbyte does not fall within the range and the
161       minimum  packet  size  value  is 0, write() shall break the buffer into
162       maximum packet size segments prior to sending the data downstream  (the
163       last  segment  may contain less than the maximum packet size). If nbyte
164       does not fall within the range  and  the  minimum  value  is  non-zero,
165       write()  shall  fail with errno set to [ERANGE].  Writing a zero-length
166       buffer (nbyte is 0) to a STREAMS device sends 0 bytes with 0  returned.
167       However,  writing  a zero-length buffer to a STREAMS-based pipe or FIFO
168       sends no message and 0 is returned.  The  process  may  issue  I_SWROPT
169       ioctl()  to  enable  zero-length messages to be sent across the pipe or
170       FIFO.
171
172       When writing to a STREAM, data messages are  created  with  a  priority
173       band of 0. When writing to a STREAM that is not a pipe or FIFO:
174
175        *  If  O_NONBLOCK  is  clear,  and  the STREAM cannot accept data (the
176           STREAM write queue is full due  to  internal  flow  control  condi‐
177           tions), write() shall block until data can be accepted.
178
179        *  If  O_NONBLOCK  is  set  and the STREAM cannot accept data, write()
180           shall return -1 and set errno to [EAGAIN].
181
182        *  If O_NONBLOCK is set and part of the buffer has been written  while
183           a  condition  in  which  the  STREAM  cannot accept additional data
184           occurs, write() shall terminate and  return  the  number  of  bytes
185           written.
186
187       In  addition,  write()  shall  fail if the STREAM head has processed an
188       asynchronous error before the call. In this case, the  value  of  errno
189       does not reflect the result of write(), but reflects the prior error.
190
191       The  pwrite()  function  shall be equivalent to write(), except that it
192       writes into a given position  and  does  not  change  the  file  offset
193       (regardless  of  whether O_APPEND is set). The first three arguments to
194       pwrite() are the same as write() with the addition of a fourth argument
195       offset  for the desired position inside the file. An attempt to perform
196       a pwrite() on a file that is incapable of seeking shall  result  in  an
197       error.
198

RETURN VALUE

200       Upon  successful completion, these functions shall return the number of
201       bytes actually written to the file associated with fildes.  This number
202       shall never be greater than nbyte.  Otherwise, -1 shall be returned and
203       errno set to indicate the error.
204

ERRORS

206       These functions shall fail if:
207
208       EAGAIN The file is neither a pipe, nor a FIFO, nor a socket, the O_NON‐
209              BLOCK  flag is set for the file descriptor, and the thread would
210              be delayed in the write() operation.
211
212       EBADF  The fildes argument is not a  valid  file  descriptor  open  for
213              writing.
214
215       EFBIG  An attempt was made to write a file that exceeds the implementa‐
216              tion-defined maximum file size or the file  size  limit  of  the
217              process, and there was no room for any bytes to be written.
218
219       EFBIG  The  file  is  a  regular file, nbyte is greater than 0, and the
220              starting position is greater than or equal to the offset maximum
221              established in the open file description associated with fildes.
222
223       EINTR  The  write operation was terminated due to the receipt of a sig‐
224              nal, and no data was transferred.
225
226       EIO    The process is a member of a background process group attempting
227              to write to its controlling terminal, TOSTOP is set, the calling
228              thread is not blocking SIGTTOU,  the  process  is  not  ignoring
229              SIGTTOU,  and the process group of the process is orphaned. This
230              error may also be returned under  implementation-defined  condi‐
231              tions.
232
233       ENOSPC There  was  no free space remaining on the device containing the
234              file.
235
236       ERANGE The transfer request size was outside the range supported by the
237              STREAMS file associated with fildes.
238
239       The pwrite() function shall fail if:
240
241       EINVAL The file is a regular file or block special file, and the offset
242              argument is negative. The file offset shall remain unchanged.
243
244       ESPIPE The file is incapable of seeking.
245
246       The write() function shall fail if:
247
248       EAGAIN The file is a pipe or FIFO, the O_NONBLOCK flag is set  for  the
249              file  descriptor,  and  the thread would be delayed in the write
250              operation.
251
252       EAGAIN or EWOULDBLOCK
253              The file is a socket, the O_NONBLOCK flag is set  for  the  file
254              descriptor,  and the thread would be delayed in the write opera‐
255              tion.
256
257       ECONNRESET
258              A write was attempted on a socket that is not connected.
259
260       EPIPE  An attempt is made to write to a pipe or FIFO that is  not  open
261              for  reading  by  any  process, or that only has one end open. A
262              SIGPIPE signal shall also be sent to the thread.
263
264       EPIPE  A write was attempted on a socket that is shut down for writing,
265              or  is no longer connected. In the latter case, if the socket is
266              of type SOCK_STREAM, a SIGPIPE signal shall also be sent to  the
267              thread.
268
269       These functions may fail if:
270
271       EINVAL The  STREAM  or  multiplexer  referenced  by  fildes  is  linked
272              (directly or indirectly) downstream from a multiplexer.
273
274       EIO    A physical I/O error has occurred.
275
276       ENOBUFS
277              Insufficient resources were available in the system  to  perform
278              the operation.
279
280       ENXIO  A  request  was made of a nonexistent device, or the request was
281              outside the capabilities of the device.
282
283       ENXIO  A hangup occurred on the STREAM being written to.
284
285       A write to a STREAMS file  may  fail  if  an  error  message  has  been
286       received  at  the  STREAM head. In this case, errno is set to the value
287       included in the error message.
288
289       The write() function may fail if:
290
291       EACCES A write was attempted on a socket and the calling  process  does
292              not have appropriate privileges.
293
294       ENETDOWN
295              A  write  was attempted on a socket and the local network inter‐
296              face used to reach the destination is down.
297
298       ENETUNREACH
299              A write was attempted on a socket and no route to the network is
300              present.
301
302       The following sections are informative.
303

EXAMPLES

305   Writing from a Buffer
306       The  following example writes data from the buffer pointed to by buf to
307       the file associated with the file descriptor fd.
308
309
310           #include <sys/types.h>
311           #include <string.h>
312           ...
313           char buf[20];
314           size_t nbytes;
315           ssize_t bytes_written;
316           int fd;
317           ...
318           strcpy(buf, "This is a test\n");
319           nbytes = strlen(buf);
320
321           bytes_written = write(fd, buf, nbytes);
322           ...
323

APPLICATION USAGE

325       None.
326

RATIONALE

328       See also the RATIONALE section in read().
329
330       An attempt to write to a pipe or FIFO has  several  major  characteris‐
331       tics:
332
333        *  Atomic/non-atomic: A write is atomic if the whole amount written in
334           one operation is not interleaved with data from any other  process.
335           This  is  useful  when there are multiple writers sending data to a
336           single reader. Applications need to know how large a write  request
337           can  be expected to be performed atomically. This maximum is called
338           {PIPE_BUF}.  This volume of POSIX.1‐2017 does not say whether write
339           requests  for  more  than {PIPE_BUF} bytes are atomic, but requires
340           that writes of {PIPE_BUF} or fewer bytes shall be atomic.
341
342        *  Blocking/immediate:  Blocking  is  only  possible  with  O_NONBLOCK
343           clear.  If  there  is enough space for all the data requested to be
344           written immediately, the implementation should  do  so.  Otherwise,
345           the  calling thread may block; that is, pause until enough space is
346           available for writing. The effective size of a pipe  or  FIFO  (the
347           maximum  amount that can be written in one operation without block‐
348           ing) may vary dynamically, depending on the implementation,  so  it
349           is not possible to specify a fixed value for it.
350
351        *  Complete/partial/deferred: A write request:
352
353
354               int fildes;
355               size_t nbyte;
356               ssize_t ret;
357               char *buf;
358
359               ret = write(fildes, buf, nbyte);
360
361           may return:
362
363           Complete  ret=nbyte
364
365           Partial   ret<nbyte
366
367                     This  shall never happen if nbyte≤{PIPE_BUF}.  If it does
368                     happen   (with   nbyte>{PIPE_BUF}),   this   volume    of
369                     POSIX.1‐2017   does  not  guarantee  atomicity,  even  if
370                     ret≤{PIPE_BUF}, because atomicity is guaranteed according
371                     to the amount requested, not the amount written.
372
373           Deferred: ret=-1, errno=[EAGAIN]
374
375                     This error indicates that a later request may succeed. It
376                     does  not  indicate  that  it  shall  succeed,  even   if
377                     nbyte≤{PIPE_BUF},  because  if  no process reads from the
378                     pipe or FIFO, the write never  succeeds.  An  application
379                     could  usefully  count  the  number  of times [EAGAIN] is
380                     caused by a particular value of nbyte>{PIPE_BUF} and per‐
381                     haps do later writes with a smaller value, on the assump‐
382                     tion that  the  effective  size  of  the  pipe  may  have
383                     decreased.
384
385           Partial and deferred writes are only possible with O_NONBLOCK set.
386
387       The relations of these properties are shown in the following tables:
388
389       ┌───────────────────────────────────────────────────────────────────────┐
390Write to a Pipe or FIFO with O_NONBLOCK clear              │
391       ├─────────────────────┬─────────────────────────────────────────────────┤
392Immediately Writable:None            Some            nbyte       │
393       ├─────────────────────┼─────────────────────────────────────────────────┤
394nbyte≤{PIPE_BUF}     │Atomic blocking Atomic blocking Atomic immediate │
395       │                     │nbyte           nbyte           nbyte
396       ├─────────────────────┼─────────────────────────────────────────────────┤
397nbyte>{PIPE_BUF}     │Blocking nbyte  Blocking nbyte  Blocking nbyte
398       └─────────────────────┴─────────────────────────────────────────────────┘
399       If  the  O_NONBLOCK  flag  is clear, a write request shall block if the
400       amount writable immediately is less than that requested. If the flag is
401       set (by fcntl()), a write request shall never block.
402
403          ┌───────────────────────────────────────────────────────────────┐
404Write to a Pipe or FIFO with O_NONBLOCK set           │
405          ├─────────────────────┬─────────────────────────────────────────┤
406Immediately Writable:None         Some          nbyte     │
407          ├─────────────────────┼─────────────────────────────────────────┤
408nbyte≤{PIPE_BUF}     │-1, [EAGAIN] -1, [EAGAIN]  Atomic nbyte
409          ├─────────────────────┼─────────────────────────────────────────┤
410nbyte>{PIPE_BUF}     │-1, [EAGAIN] <nbyte or -1, ≤nbyte or -1, │
411          │                     │             [EAGAIN]      [EAGAIN]      │
412          └─────────────────────┴─────────────────────────────────────────┘
413       There  is no exception regarding partial writes when O_NONBLOCK is set.
414       With the exception  of  writing  to  an  empty  pipe,  this  volume  of
415       POSIX.1‐2017 does not specify exactly when a partial write is performed
416       since that would require specifying internal details of the implementa‐
417       tion.  Every  application  should  be prepared to handle partial writes
418       when O_NONBLOCK is  set  and  the  requested  amount  is  greater  than
419       {PIPE_BUF}, just as every application should be prepared to handle par‐
420       tial writes on other kinds of file descriptors.
421
422       The intent of forcing writing at least one byte if any can  be  written
423       is to assure that each write makes progress if there is any room in the
424       pipe. If the pipe is empty, {PIPE_BUF} bytes must be written;  if  not,
425       at least some progress must have been made.
426
427       Where  this volume of POSIX.1‐2017 requires -1 to be returned and errno
428       set to [EAGAIN], most historical implementations return zero (with  the
429       O_NDELAY  flag  set, which is the historical predecessor of O_NONBLOCK,
430       but is not itself in this volume of POSIX.1‐2017).  The  error  indica‐
431       tions in this volume of POSIX.1‐2017 were chosen so that an application
432       can distinguish these cases  from  end-of-file.  While  write()  cannot
433       receive an indication of end-of-file, read() can, and the two functions
434       have similar return values. Also, some existing systems  (for  example,
435       Eighth  Edition)  permit  a write of zero bytes to mean that the reader
436       should get an end-of-file indication; for those systems, a return value
437       of  zero  from  write()  indicates a successful write of an end-of-file
438       indication.
439
440       Implementations are allowed, but not required, to perform error  check‐
441       ing for write() requests of zero bytes.
442
443       The  concept  of  a  {PIPE_MAX} limit (indicating the maximum number of
444       bytes that can be written to a pipe in a single operation) was  consid‐
445       ered,  but  rejected,  because  this  concept would unnecessarily limit
446       application writing.
447
448       See also the discussion of O_NONBLOCK in read().
449
450       Writes can be serialized with respect to other reads and writes.  If  a
451       read()  of  file  data  can  be  proven (by any means) to occur after a
452       write() of the data, it must reflect that write(), even  if  the  calls
453       are  made by different processes. A similar requirement applies to mul‐
454       tiple write operations to the same file position.  This  is  needed  to
455       guarantee  the  propagation  of  data  from write() calls to subsequent
456       read() calls. This requirement is  particularly  significant  for  net‐
457       worked  file  systems,  where some caching schemes violate these seman‐
458       tics.
459
460       Note that this is specified in terms of read() and  write().   The  XSI
461       extensions  readv()  and  writev()  also  obey  these  semantics. A new
462       ``high-performance'' write analog that did not follow these  serializa‐
463       tion  requirements would also be permitted by this wording. This volume
464       of POSIX.1‐2017 is also silent about any effects  of  application-level
465       caching (such as that done by stdio).
466
467       This volume of POSIX.1‐2017 does not specify the value of the file off‐
468       set after an error is returned; there are too many cases. For  program‐
469       ming  errors, such as [EBADF], the concept is meaningless since no file
470       is  involved.  For  errors  that  are  detected  immediately,  such  as
471       [EAGAIN],  clearly the pointer should not change. After an interrupt or
472       hardware error, however, an updated value would be very useful  and  is
473       the behavior of many implementations.
474
475       This volume of POSIX.1‐2017 does not specify the behavior of concurrent
476       writes to a regular file from multiple threads, except that each  write
477       is  atomic  (see  Section  2.9.7, Thread Interactions with Regular File
478       Operations).  Applications should use some form of concurrency control.
479
480       This volume of POSIX.1‐2017 intentionally does not specify any pwrite()
481       errors related to pipes, FIFOs, and sockets other than [ESPIPE].
482

FUTURE DIRECTIONS

484       None.
485

SEE ALSO

487       chmod(), creat(), dup(), fcntl(), getrlimit(), lseek(), open(), pipe(),
488       read(), ulimit(), writev()
489
490       The Base Definitions volume of POSIX.1‐2017,  <limits.h>,  <stropts.h>,
491       <sys_uio.h>, <unistd.h>
492
494       Portions  of  this text are reprinted and reproduced in electronic form
495       from IEEE Std 1003.1-2017, Standard for Information Technology --  Por‐
496       table  Operating System Interface (POSIX), The Open Group Base Specifi‐
497       cations Issue 7, 2018 Edition, Copyright (C) 2018 by the  Institute  of
498       Electrical  and  Electronics Engineers, Inc and The Open Group.  In the
499       event of any discrepancy between this version and the original IEEE and
500       The  Open Group Standard, the original IEEE and The Open Group Standard
501       is the referee document. The original Standard can be  obtained  online
502       at http://www.opengroup.org/unix/online.html .
503
504       Any  typographical  or  formatting  errors that appear in this page are
505       most likely to have been introduced during the conversion of the source
506       files  to  man page format. To report such errors, see https://www.ker
507       nel.org/doc/man-pages/reporting_bugs.html .
508
509
510
511IEEE/The Open Group                  2017                            WRITE(3P)
Impressum