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
11

NAME

13       pwrite, write — write on a file
14

SYNOPSIS

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

DESCRIPTION

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

RETURN VALUE

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

ERRORS

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

EXAMPLES

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

FUTURE DIRECTIONS

482       None.
483

SEE ALSO

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