Linux system Programming--read/write

Source: Internet
Author: User

4. read/The write read function reads data from an open device or file. #include<unistd.h> ssize_t Read (intFdvoid*buf, size_t count); Return value: The number of bytes read successfully returned, error returned-1 and set errno, if the end of the file is reached before the call is read, the read returns 0 parameter count is the number of bytes requested to read, the read data is saved in the buffer buf, and the current read and write location of the file is moved backwards. Note This read-write location and use C standard IThe read/write location of the/O library may be different, this read-write location is recorded in the kernel, while the use of C-standard I/O library when the read and write location is the user space i/o the position in the buffer. Fread is realized through read, Fread is the C language library, and read is the system call but the difference in read every time the data is called by the caller, for example, the call requires reading 10 bytes of data, read reads 10 bytes of data into the array, and fread is not the same, To speed up the reading, Fread reads more data each time than required, and then puts it into the buffer so that the next time you read the data you just need to go to the buffer to fetch it. Fread reads a buffer-size data every time, 32 bits is generally 4,096 bytes, which is equivalent to calling read (Fd,buf,4096For example, you need to read 512 bytes of data, read 4 times, and call read: for(i=0; i<4; ++i) Read (Fd,buf, -) A total of 4 system calls and fread once read 4096 bytes into the buffer, so it's easier to read a byte with fgetc, fgetc may read 1024 bytes from the kernel to I/o buffer, returning the first byte, at which point the file reads and writes in the kernel is 1024, while the read and write location recorded in the file structure is 1. Note that the return value type is ssize_t, which represents the signed size_t, which returns the number of positive bytes,0(indicates that the end of the file is reached) can also return a negative value-1(indicates an error). When the Read function returns, the return value shows how many bytes in the buf were just read. In some cases, the number of bytes actually read (the return value) is less than the number of bytes requested to be read, for example: When reading a regular file, the end of the file is reached before the Count bytes are read. For example, if you have 30 bytes from the end of the file and you request to read 100 bytes, read returns 30, and the next time read returns 0. Read from the terminal device, usually in the unit of behavior, read to the newline character returned. Read from the network, depending on the transport layer protocol and the kernel cache mechanism, the return value may be less than the requested number of bytes, later the Socket programming section will be explained in detail. The Write function writes data to an open device or file. #include<unistd.h> ssize_t Write (intFdConst void*buf, size_t count); Return value: The number of bytes written successfully returned, error returned-1 and when you set errno to write regular files, the return value of write is usually equal to the number of bytes requested by count, while writing to the terminal device or network is not necessarily. Reading regular files is not blocked, no matter how many bytes read, read is bound to return within a limited time. From the terminal device or the network reading is not necessarily, if the data entered from the end of the line does not have a newline character, call read read terminal equipment will be blocked, if the network is not receiving packets, call read from the network will block the reading, as to how long it will block is not sure, if there is no data arrives has been blocked there. Similarly, writing regular files is not blocked, but writing to the end-device or network is not necessarily the case. Now, make clear the concept of blocking (block). When a process calls a blocked system function, the process is placed in the sleep state, when the kernel dispatches another process to run until the event that the process waits for (such as receiving a packet on the network, or calling sleep to specify the sleeping time) it is possible to continue running. Relative to the sleep state is the run (Running) state, in the Linux kernel, the running process is divided into two situations: being scheduled to execute. The CPU is in the context of the process, the program counter (EIP) holds the instruction address of the process, the General register holds the intermediate result of the process operation, the process is executing the instructions, is reading and writing the process's address space. Ready state. The process does not need to wait for any events to occur and can be executed at any time, but the CPU is still executing another process, so the process waits for the kernel to be dispatched in a ready queue. The system may have more than one ready process at the same time, then who is the dispatcher executing it? The kernel scheduling algorithm is based on the priority and time slices, and will dynamically adjust its priority and time slice according to the operation of each process, so that each process can be more fair to get the opportunity to execute, while taking into account the user experience, can not let the user interaction process response too slow. The following applet reads the data from the terminal and writes it back to the terminal. Example28.2. Blocking read Terminal # include<unistd.h>#include<stdlib.h>intMainvoid){ Charbuf[Ten]; intN; n= Read (Stdin_fileno, buf,Ten); if(N <0) {perror ("Read Stdin_fileno"); Exit (1); } write (Stdout_fileno, buf, N); return 0;} The execution results are as follows: $./A. outHello (carriage return) Hello $./A. outHello World (carriage return) Hello worl$ d bash:d: Command not found the result of the first execution a.out is normal, and the second execution of the process is a bit special, now analyze: Shell process Create a.out process, A.ou The t process begins execution while the shell process sleeps waiting for the a.out process to exit. A.out calls read when sleep waits until the terminal device enters a newline characters from read, read reads only 10 characters, and the remaining characters are still stored in the kernel's terminal device input buffer. The a.out process prints and exits, when the shell process resumes running, the shell continues to read the user input commands from the terminal, and then reads the rest of the terminal device input buffer D and newline characters, as a command to interpret the execution, the results found no execution, no D this command. 
#include <unistd.h>#include<stdlib.h>#include<unistd.h>#include<fcntl.h>intMainvoid){        Charbuf[Ten]; intN;        Fcntl (Stdin_fileno,f_setfl,o_nonblock); N= Read (Stdin_fileno, buf,Ten); if(N <0) {perror ("Read Stdin_fileno"); Exit (1);        } write (Stdout_fileno, buf, N); return 0;}

The above means that the input terminal resource is temporarily unavailable

Fcntl (stdin_fileno,f_setfl,o_nonblock); This sentence is commented out
Block until data entry is available
If the O_NONBLOCK flag is specified when a device is open, read/write will not block. Take read, for example, if the device has no data to read for the time being, return-1, while the errno is Ewouldblock (or Eagain, the two macros define the same values), it means that it should have been blocked here (would block, subjunctive), and actually did not block but returned the error directly, The caller should try to read it again (again). This behavior is called polling (Poll), and the caller simply queries, not blocking here death, so that multiple devices can be monitored simultaneously: while(1{Non-blocking read (device 1);if(Equipment 1 has data arrival) processing data; Non-blocking read (device 2);if(equipment 2 has data arrival) processing data; ... } If read (device 1) is blocked, then as long as the device 1 No data arrives will be blocked on the device 1 read call, even if the device 2 has data arrival can not process, using non-blocking I/o can avoid equipment 2 is not processed in time. Non-blocking I/O There is a drawback, if all the devices have been no data arrives, the caller needs to repeatedly query to do the work, if blocking there, the operating system can dispatch other processes to execute, will not do a useless. When using non-blocking i/o, usually do not keep querying in a while loop (this is called Tight loop), but each delay to wait for a moment to query, so as not to do too much work, in the delay when waiting for the scheduling of other processes to execute.  while(1{Non-blocking read (device 1);if(Equipment 1 has data arrival) processing data; Non-blocking read (device 2);if(equipment 2 has data arrival) processing data; ... sleep (n); The problem is that the device 1 has data arrival may not be processed in time, the longest delay of n seconds to process, and repeatedly query or do a lot of useless. Select that you want to study later (2) function can block the simultaneous monitoring of multiple devices, but also can set the blocking wait time-out period, so as to satisfactorily solve the problem. The following is a non-blocking IAn example of/O. At the moment we have learned that the devices that may cause blockage are only terminals, so we use the terminal to do this experiment. When the program starts executing at 0,1, the file automatically opened on the 2 file descriptor is the terminal, but there is no o_nonblock flag. So just like the example28.2Read-only standard input is blocked, as in "blocking read Terminal". We can reopen the device file/dev/TTY (representing the current terminal), specifying the O_NONBLOCK flag on open. The O_nonblock opens the file in an unstoppable way, that is, whether or not data is read or waiting, it will be returned to the process immediately. Example28.3non-blocking read terminal from the terminal device or network reading is not necessarily, if the data entered from the terminal does not have a newline character, call the read terminal device will block # include<unistd.h>#include<fcntl.h>#include<errno.h>#include<string.h>#include<stdlib.h>#defineMsg_try "TRY again\n"intMainvoid){Charbuf[Ten];intFD, N;FD= Open ("/dev/tty", o_rdonly|o_nonblock);if(fd<0) {perror ("Open/dev/tty"); exit (1);} Tryagain:n= Read (FD, BUF,Ten);if(N <0) {if(errno = =Eagain) {Sleep (1); write (Stdout_fileno, Msg_try, strlen (msg_try));GotoTryagain;} Perror ("Read/dev/tty"); exit (1);} Write (Stdout_fileno, buf, N); close (FD);return 0;} Until you press ENTER to put the previous input output (up to 10), and then stop. The following is a non-blocking I/o Implement the wait timeout example. The logic of time-out exit ensures that the processing delay is smaller when data arrives. Example28.4. Non-blocking read terminal and wait timeout read: Can return a positive number of bytes,0(indicates that the end of the file is reached) can also return a negative value-1(indicates an error) #include<unistd.h>#include<fcntl.h>#include<errno.h>#include<string.h>#include<stdlib.h>#defineMsg_try "TRY again\n"#defineMsg_timeout "timeout\n"intMainvoid){ Charbuf[Ten]; intFD, n, i; FD= Open ("/dev/tty", o_rdonly|O_nonblock); if(fd<0) {perror ("Open/dev/tty"); Exit (1); }  for(i=0; i<5; i++) {n= Read (FD, BUF,Ten); if(n>=0)    Break; if(errno!=Eagain) {Perror ("Read/dev/tty"); Exit (1); } Sleep (1); Write (Stdout_fileno, Msg_try, strlen (msg_try)); } if(i==5) Write (Stdout_fileno, Msg_timeout, strlen (msg_timeout)); ElseWrite (Stdout_fileno, buf, N); close (FD);return 0;}
Reprinted from: http://blog.163.com/bowen_tong/blog/static/20681717420126601118551/

Linux system Programming--read/write

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.