Operating System

System Calls


read() and write() system calls are used to read and write data respectively to a file descriptor. To understand the concept of write()/read() system calls let us first start with write() system call.


write() system call is used to write to a file descriptor. In other words write() can be used to write to any file (all hardware are also referred as file in Linux) in the system but rather than specifying the file name, you need to specify its file descriptor.


Syntax:



The first parameter (fd) is the file descriptor where you want to write. The data that is to be written is specified in the second parameter. Finally, the third parameter is the total bytes that are to be written.
To understand better lets look at the first program below:


Program1: To write some data on the standard output device (by default - monitor)


//Name the program file as "write.c"



How it works?


The write() system call takes three parameters: “1” which is the file descriptor of the file where we want to write. Since we want to write on standard output device which is the screen, hence the file descriptor, in this case, is ‘1’, which is fixed (0 is the file descriptor for standard input device (e.g. keyboard) and 2 is for standard error device)). Next thing is what we want to write on the screen. In this case its “hello\n” i.e. hello and newline(\n), so a total of 6 characters, which becomes the third parameter. The third parameter is how much you want to write, which may be less than the data specified in the second parameter. You can play around and see the change in output.


Output:


Once you compile and run this, the output on the screen will be the word “hello”, as shown below



On success, the write() system call returns the 'number of bytes written' i.e. the count of how many bytes it could write. This you can save in an integer variable and checked. The write() system call on failure returns -1. Note: students get confused by thinking that write() return the data that is written. Remember, it returns the count of characters written. Refer to the program below.

Video Link