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

NAME

6       pwrite, write - write on a file
7

SYNOPSIS

9       #include <unistd.h>
10
11
12
13       ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
14              off_t offset);
15       ssize_t write(int fildes, const void *buf, size_t nbyte);
16
17

DESCRIPTION

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

RETURN VALUE

194       Upon  successful  completion,  write()    and pwrite() shall return the
195       number of bytes actually written to the file  associated  with  fildes.
196       This  number  shall never be greater than nbyte. Otherwise, -1 shall be
197       returned and errno set to indicate the error.
198

ERRORS

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

EXAMPLES

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

APPLICATION USAGE

320       None.
321

RATIONALE

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

FUTURE DIRECTIONS

471       None.
472

SEE ALSO

474       chmod()  , creat() , dup() , fcntl() , getrlimit() , lseek() , open() ,
475       pipe()  ,  ulimit()  ,  writev()  ,  the  Base  Definitions  volume  of
476       IEEE Std 1003.1-2001, <limits.h>, <stropts.h>, <sys/uio.h>, <unistd.h>
477
479       Portions  of  this text are reprinted and reproduced in electronic form
480       from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology
481       --  Portable  Operating  System  Interface (POSIX), The Open Group Base
482       Specifications Issue 6, Copyright (C) 2001-2003  by  the  Institute  of
483       Electrical  and  Electronics  Engineers, Inc and The Open Group. In the
484       event of any discrepancy between this version and the original IEEE and
485       The  Open Group Standard, the original IEEE and The Open Group Standard
486       is the referee document. The original Standard can be  obtained  online
487       at http://www.opengroup.org/unix/online.html .
488
489
490
491IEEE/The Open Group                  2003                             WRITE(P)
Impressum