Puneet Varma (Editor)

Write (system call)

Updated on
Edit
Like
Comment
Share on FacebookTweet on TwitterShare on LinkedInShare on Reddit
Write (system call)

The write is one of the most basic routines provided by a Unix-like operating system kernel. It writes data from a buffer declared by the user to a given device, maybe a file. This is primary way to output data from a program by directly using a system call. The destination is identified by a numeric code. The data to be written, for instance a piece of text, is defined by a pointer and a size, given in number of bytes.

Contents

write thus takes three arguments:

  1. The file code (file descriptor or fd).
  2. The pointer to a buffer where the data is stored (buf).
  3. The number of bytes to write from the buffer (nbytes).

POSIX usage

The write call interface is standardized by the POSIX specification. Data is written to a file by calling the write function. The function prototype is :

In above syntax, ssize_t is a typedef. It is a signed data type defined in stddef.h. Note that write() does not return an unsigned value; it returns -1 if an error occurs so it must return a signed value.
The write function returns the number of bytes successfully written into the array, which may at times be less than the specified nbytes. It returns -1 if an exceptional condition is encountered, see section on errors below.

Errors encountered during operation

Listed below are some errors that could be encountered during writing to a file. The errors are macros listed in errno.h .

Higher level I/O functions calling write

The write system call is not an ordinary function, in spite of the close resemblance. In Linux, the system call uses the operating code INT 80H of the assembly language, in order to transfer control over to the kernel. The write system call, and its counterpart read, being low level functions, are only capable of understanding bytes. Write cannot be used to write records, like classes. Thus, higher level input-output functions (like printf) are required. Often, the high-level interface is preferred, as compared to the cluttered low-level interface. These functions call other functions internally, and these in turn can make calls to write, giving rise to a layered assembly of functions.

With the use of this assembly the higher level functions can collect bytes of data and then write the required data into a file.

References

Write (system call) Wikipedia