Linux read() function

Linux read() function DEFAULT
In traditional POSIX compatible operating systems, to get information from a document contained in a file system, a program used the read system call. A document descriptor that is usually accessed from a prior call to open is defined by the file. This read system call reads out the information in bytes and the integer of which the caller specifies from the document, and then saves it in a buffer provided by the calling mechanism.

Function Definition

Before defining the read function in your code, you have to include some required packages.

#include <unistd.h>

Here is how you define the POSIX read function:

>> ssize_t pread(int fildes, void*buf, size_t nbyte, off_t offset);
>> ssize_t read(int fd, void*buf, size_t nbytes);

Three parameter arguments can be taken from the read method call:

int fd: The file descriptor of the file from where the information is to be read. We could either be using a file descriptor acquired via an open system call, or we could just use 0, 1, or 2 referring to typical input, regular output, or regular error, respectively.

Void *buf: The buffer or character array in which the read data should be saved and kept.

Size_t nbyte: The number of bytes that needed to be read from the document before truncating. All information can be stored in the buffer if the information to be read is shorter than nbytes.

Description

The read() method tries to read ‘nbyte’ bytes into the buffer cache referred to by ‘buf’ from either the file connected with the open document descriptor ‘Fildes’ or ‘fd’. It does not define the nature of several simultaneous reads on the same stream, FIFO, or terminal unit.

On documents that enable the reading, the reading process begins at the offset of the document, and the offset is increased by the number of bytes read. If the document offset is at or beyond the file’s edge, there are no bytes read, and read() yields none.

When the count is 0, read() will recognize the errors mentioned below. If there are no mistakes, or if read() is not accounted for with Errors, a read() yields zero with a count of 0 and therefore has no other repercussions.

If the count is higher than SSIZE_MAX, as per POSIX.1, then the outcome is determined by the implementation.

Return Value

The numeral of bytes ‘read’ and ‘pread’ reverted upon achievement must be a non-negative integer while zero points to the end of the file. The document position is progressed by this number, or else, to signify an error, the methods return -1 and assign ‘errno’. When this figure is less than the number of bytes requested, it is not a mistake byte. It could be possible that fewer bytes are available for now.

Errors

The pread and read function will be unsuccessful if these errors occur:

EAGAIN:

The document or file descriptor ‘fd’ belongs to a non-socket file that has been labeled as non-blocking (O NONBLOCK) and will block the reading.

EWOULDBLOCK:

The descriptor ‘fd’ belongs to a socket that has been labeled as non-blocking (O_NONBLOCK) and will block the reading.

EBADF:

The ‘fd’ may not be a usable descriptor, or it may not be open for reading.

EFAULT:

This happens when your ‘buf’ is outside your reachable address space.

EINTR:

Before the reading of information data, the call may have broken up by a signal.

EINVAL:

This error occurs when your ‘fd’ descriptor is involved in an object, which is not appropriate for reading, or the document was untied with the O_DIRECT flag, and one or the other address stated in ‘buf’, the value indicated in ‘count’, or the document offset is not appropriately associated.

EINVAL:

The descriptor ‘fd’ may have been formed using a call to timerfd_create(2), and the incorrect size buffer has been given to read.

EIO:

It is an input/output error. It occurs when the background process group attempts to read from its regulatory terminal, and one or the other is overlooking or blocking SIGTTIN, or its process group is bereaved. Another reason for this error could be low-level input/output error meanwhile reading from a hard disk or tape. Another potential cause of EIO on networked data files is the removal of advisory locking on the file descriptor and the failure of that lock.

EISDIR:

The file descriptor ‘fd’ belongs to a directory.

Notes:

Many other errors may also occur, contingent on the object linked to descriptor ‘fd’. Both size_t and ssize_t forms are unmarked and marked numerical data types defined by POSIX.1. On Linux, at most 0x7ffff000 (2,147,479,552) bytes can be transmitted by reading function (and equivalent system calls), returning the number of bytes originally transmitted (on both 32-bit and 64-bit platforms). With NFS filesystems, just the first moment the timestamp is changed by reading tiny streams of information, subsequent calls wouldn’t do so. It is triggered by caching of client-side attributes since, although not all, NFS clients quit updating to the server via st_atime (last file access time) and client-side reads fulfilled from the buffer of the client would not trigger changes to st-atime on the server as no server-side readings are available. By removing client-side attribute caching, UNIX metadata may be accessed, but this would significantly increase the load on the server and affect productivity in most cases.

Example 01:

Here is a C program to demonstrate the read function call on the Linux System. Write the below-command as it is in a new file. Add libraries, and in the main function, initialize a descriptor and size. The descriptor is opening the file, and size is used to read file data.

The output for the above-code would be as shown in the below image.

Example 02:

Another example to illustrate the working of the read function is given below.

Create another file and write down the code below as it is in it. Here are two descriptors, fd1 & fd2, that both have their own open table file access. So for foobar.txt, every descriptor does have its file location. The very first byte of foobar.txt is translated from fd2, and the result is c = f, not c = o.

Conclusion

We have read the POSIX read function in C programming efficiently. Hopefully, there are no doubts left.

Sours: https://linuxhint.com/posix-read-functioning-in-c-programming/

Advanced Programming in the UNIX® Environment: UNIX File I/O

This chapter is from the book 

3.7 Function

Data is read from an open file with the function.

#include <unistd.h> ssize_t read(int filedes,
void *buff, size_t nbytes); Returns: number of bytes read, 0 if end of file, –1 on error

If the is successful, the number of bytes read is returned. If the end of file is encountered, 0 is returned.

There are several cases in which the number of bytes actually read is less than the amount requested:

  • When reading from a regular file, if the end of file is reached before the requested number of bytes has been read. For example, if there are 30 bytes remaining until the end of file and we try to read 100 bytes, returns 30. The next time we call it will return 0 (end of file).

  • When reading from a terminal device, normally up to one line is read at a time (we'll see how to change this in Chapter 11).

  • When reading from a network, buffering within the network may cause less than the requested amount to be returned.

  • Some record-oriented devices, such as a magnetic tape, return up to a single record at a time.

The read operation starts at the file's current offset. Before a successful return, the offset is incremented by the number of bytes actually read.

POSIX.1 changed the prototype for this function in several ways. The classic definition is

int read(int filedes, char *buff, unsigned nbytes);

First, the second argument was changed from a to a to be consistent with ANSI C: the type is used for generic pointers. Next, the return value must be a signed integer () to return either a positive byte count, 0 (for end of file), or -1 (for an error). Finally, the third argument historically has been an unsigned integer, to allow a 16-bit implementation to read or write up to 65534 bytes at a time. With the 1990 POSIX.1 standard the new primitive system data type was introduced to provide the signed return value, and the unsigned was used for the third argument. (Recall the constant from Figure 2.7.)

Sours: https://www.informit.com/articles/article.aspx?p=99706&seqNum=7
  1. Stream adventure time season 1
  2. 100 grams green beans calories
  3. Horizontal lines on iphone camera
  4. At&t tv instructions
  5. Composite bar height adirondack chairs

read(2) — Linux manual page


READ(2) Linux Programmer's Manual READ(2)

NAME         top

read - read from a file descriptor

SYNOPSIS         top

#include <unistd.h>ssize_t read(int fd, void *buf, size_t count);

DESCRIPTION         top

read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf. On files that support seeking, the read operation commences at the file offset, and the file offset is incremented by the number of bytes read. If the file offset is at or past the end of file, no bytes are read, and read() returns zero. If count is zero, read() may detect the errors described below. In the absence of any errors, or if read() does not check for errors, a read() with a count of 0 returns zero and has no other effects. According to POSIX.1, if count is greater than SSIZE_MAX, the result is implementation-defined; see NOTES for the upper limit on Linux.

RETURN VALUE         top

On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. See also NOTES. On error, -1 is returned, and errno is set to indicate the error. In this case, it is left unspecified whether the file position (if any) changes.

ERRORS         top

EAGAIN The file descriptor fd refers to a file other than a socket and has been marked nonblocking (O_NONBLOCK), and the read would block. See open(2) for further details on the O_NONBLOCK flag. EAGAIN or EWOULDBLOCK The file descriptor fd refers to a socket and has been marked nonblocking (O_NONBLOCK), and the read would block. POSIX.1-2001 allows either error to be returned for this case, and does not require these constants to have the same value, so a portable application should check for both possibilities. EBADF fd is not a valid file descriptor or is not open for reading. EFAULT buf is outside your accessible address space. EINTR The call was interrupted by a signal before any data was read; see signal(7). EINVAL fd is attached to an object which is unsuitable for reading; or the file was opened with the O_DIRECT flag, and either the address specified in buf, the value specified in count, or the file offset is not suitably aligned. EINVAL fd was created via a call to timerfd_create(2) and the wrong size buffer was given to read(); see timerfd_create(2) for further information. EIO I/O error. This will happen for example when the process is in a background process group, tries to read from its controlling terminal, and either it is ignoring or blocking SIGTTIN or its process group is orphaned. It may also occur when there is a low-level I/O error while reading from a disk or tape. A further possible cause of EIO on networked filesystems is when an advisory lock had been taken out on the file descriptor and this lock has been lost. See the Lost locks section of fcntl(2) for further details. EISDIR fd refers to a directory. Other errors may occur, depending on the object connected to fd.

CONFORMING TO         top

SVr4, 4.3BSD, POSIX.1-2001.

NOTES         top

The types size_t and ssize_t are, respectively, unsigned and signed integer data types specified by POSIX.1. On Linux, read() (and similar system calls) will transfer at most 0x7ffff000 (2,147,479,552) bytes, returning the number of bytes actually transferred. (This is true on both 32-bit and 64-bit systems.) On NFS filesystems, reading small amounts of data will update the timestamp only the first time, subsequent calls may not do so. This is caused by client side attribute caching, because most if not all NFS clients leave st_atime (last file access time) updates to the server, and client side reads satisfied from the client's cache will not cause st_atime updates on the server as there are no server-side reads. UNIX semantics can be obtained by disabling client-side attribute caching, but in most situations this will substantially increase server load and decrease performance.

BUGS         top

According to POSIX.1-2008/SUSv4 Section XSI 2.9.7 ("Thread Interactions with Regular File Operations"): All of the following functions shall be atomic with respect to each other in the effects specified in POSIX.1-2008 when they operate on regular files or symbolic links: ... Among the APIs subsequently listed are read() and readv(2). And among the effects that should be atomic across threads (and processes) are updates of the file offset. However, on Linux before version 3.14, this was not the case: if two processes that share an open file description (see open(2)) perform a read() (or readv(2)) at the same time, then the I/O operations were not atomic with respect updating the file offset, with the result that the reads in the two processes might (incorrectly) overlap in the blocks of data that they obtained. This problem was fixed in Linux 3.14.

SEE ALSO         top

close(2), fcntl(2), ioctl(2), lseek(2), open(2), pread(2), readdir(2), readlink(2), readv(2), select(2), write(2), fread(3)

COLOPHON         top

This page is part of release 5.13 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at https://www.kernel.org/doc/man-pages/.

Pages that refer to this page: grep(1),  pv(1),  strace(1),  telnet-probe(1),  close(2),  epoll_ctl(2),  eventfd(2),  fanotify_init(2),  fcntl(2),  getrandom(2),  inotify_add_watch(2),  ioctl_tty(2),  open(2),  perf_event_open(2),  perfmonctl(2),  pidfd_open(2),  pipe(2),  prctl(2),  pread(2),  ptrace(2),  readahead(2),  readv(2),  recv(2),  seccomp(2),  seccomp_unotify(2),  select(2),  select_tut(2),  sendfile(2),  setpgid(2),  signalfd(2),  socket(2),  socketpair(2),  syscalls(2),  timerfd_create(2),  userfaultfd(2),  write(2),  aio_error(3),  aio_read(3),  aio_return(3),  curs_getch(3x),  dbopen(3),  fgetc(3),  fopen(3),  fread(3),  getline(3),  gets(3),  libexpect(3),  mkfifo(3),  mpool(3),  readdir(3),  rtime(3),  stdin(3),  stdio(3),  termios(3),  xdr(3),  xfsctl(3),  dsp56k(4),  fuse(4),  lirc(4),  null(4),  random(4),  rtc(4),  st(4),  proc(5),  systemd.exec(5),  aio(7),  cpuset(7),  epoll(7),  fanotify(7),  inode(7),  inotify(7),  pipe(7),  signal(7),  signal-safety(7),  socket(7),  spufs(7),  system_data_types(7),  vsock(7),  x25(7),  mount.fuse3(8),  netsniff-ng(8),  xfs_io(8)


Copyright and license for this manual page

Sours: https://man7.org/linux/man-pages/man2/read.2.html
C Programming in Linux Tutorial #024 - open() read() write() Functions

read command in Linux with Examples

read command in Linux system is used to read from a file descriptor. Basically, this command read up the total number of bytes from the specified file descriptor into the buffer. If the number or count is zero then this command may detect the errors. But on success, it returns the number of bytes read. Zero indicates the end of the file. If some errors found then it returns -1.

Syntax:

read

Examples:

  • read command without any option: The read command asks for the user’s input and exit once the user provides some input.

  • In the following example we are acquiring the user’s name and then showing the user’s name with a greeting.echo "what is your name..?";read name;echo "hello $name"

Sours: https://www.geeksforgeeks.org/read-command-in-linux-with-examples/

Function linux read()

read(2) - Linux man page

Name

read - read from a file descriptor

Synopsis

#include <unistd.h> ssize_t read(int fd, void *buf, size_t count);

Description

read() attempts to read up to countbytes from file descriptor fdinto the buffer starting at buf.

On files that support seeking, the read operation commences at the current file offset, and the file offset is incremented by the number of bytes read. If the current file offset is at or past the end of file, no bytes are read, and read() returns zero.

If count is zero, read() may detect the errors described below. In the absence of any errors, or if read() does not check for errors, a read() with a count of 0 returns zero and has no other effects.

If count is greater than SSIZE_MAX, the result is unspecified.

Return Value

On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. On error, -1 is returned, and errnois set appropriately. In this case it is left unspecified whether the file position (if any) changes.

Errors

EAGAIN
The file descriptor fd refers to a file other than a socket and has been marked nonblocking (O_NONBLOCK), and the read would block.
EAGAIN or EWOULDBLOCK
The file descriptor fd refers to a socket and has been marked nonblocking (O_NONBLOCK), and the read would block. POSIX.1-2001 allows either error to be returned for this case, and does not require these constants to have the same value, so a portable application should check for both possibilities.
EBADF
fd is not a valid file descriptor or is not open for reading.
EFAULT
buf is outside your accessible address space.
EINTR
The call was interrupted by a signal before any data was read; see signal(7).
EINVAL
fd is attached to an object which is unsuitable for reading; or the file was opened with the O_DIRECT flag, and either the address specified in buf, the value specified in count, or the current file offset is not suitably aligned.
EINVAL
fd was created via a call to timerfd_create(2) and the wrong size buffer was given to read(); see timerfd_create(2) for further information.
EIO
I/O error. This will happen for example when the process is in a background process group, tries to read from its controlling terminal, and either it is ignoring or blocking SIGTTIN or its process group is orphaned. It may also occur when there is a low-level I/O error while reading from a disk or tape.
EISDIR
fd refers to a directory.

Other errors may occur, depending on the object connected to fd. POSIX allows a read() that is interrupted after reading some data to return -1 (with errno set to EINTR) or to return the number of bytes already read.

Conforming to

SVr4, 4.3BSD, POSIX.1-2001.

Notes

On NFS file systems, reading small amounts of data will only update the timestamp the first time, subsequent calls may not do so. This is caused by client side attribute caching, because most if not all NFS clients leave st_atime (last file access time) updates to the server and client side reads satisfied from the client's cache will not cause st_atime updates on the server as there are no server side reads. UNIX semantics can be obtained by disabling client side attribute caching, but in most situations this will substantially increase server load and decrease performance.

See Also

close(2), fcntl(2), ioctl(2), lseek(2), open(2), pread(2), readdir(2), readlink(2), readv(2), select(2), write(2), fread(3)

Referenced By

aio(7), aio_error(3), aio_read(3), aio_return(3), archive_read(3), cpuset(7), csh(1), dbopen(3), dsp56k(4), epoll(4), epoll(7), epoll_ctl(2), eventfd(2), explain(1), explain(3), explain_lca2010(1), explain_open_or_die(3), explain_read(3), explain_read_or_die(3), fgetln(3), fgets(3), fio(1), fopen(3), getline(3), grep(1), hosts_options(5), htop(1), hylafax-log(5), inotify(7), inotify_add_watch(2), io_canread(3), iostat(1), iv_fd_pump_pump(3), lam_rfposix(2), lamf_rfwrite(2), libarchive(3), libexpect(3), libssh2_sftp_read(3), mkfifo(3), mpool(3), ncl_cgm(3), nfslogsum(8), perf_event_open(2), perfmonctl(2), perlfunc(1), perlpacktut(1), pidfile(3), pipe(2), pipe(7), pipethrough(3), prctl(2), proc(5), pth(3), ptrace(2), readahead(2), readdir(3), recv(2), rmt(8), rtc(4), rtime(3), scrub(1), select_tut(2), sendfile(2), setpgrp(2), sg_dd(8), signalfd(2), socket(2), socket(7), socketpair(2), spew(1), spufs(2), spufs(7), st(4), stat(2), stdin(3), stdio(3), strace(1), tar_append_file(3), tar_block_write(3), tcflush(3), tty_ioctl(4), vpsetcallback(3), vrb(3), vrb_read(3), vrb_read_min(3), wgetch(3), writev(2), x25(7), xdr(3), xfs_io(8), xfsctl(3), zero(4), zvbi-chains(1), zzip_freopen(3)
Sours: https://linux.die.net/man/2/read
Linux how to read write and edit text files

proper way to use GNU/Linux read() function

I don't know why is this happening.

But I know. is just a pointer, but that pointer needs to be initialized to something before you can use it. Without doing so you're invoking undefined behavior and everything might happen.

Instead of the and elements you should just use a , before making the read call, resize it to the number of bytes you want to read, then take the address of the first element of that vector and pass that to read:

and use it like this; note that using requires some additional work to properly deal with signal and error conditions.


Looking at your first paragraph of gibberish:

If the count is greater than one, the pointer supplied in the function argument will point to the last byte that was read from the port in the memory

What makes you think so? This is not how it works. Most likely you passed some invalid pointer that wasn't properly initialized. Anything can happen.

so pointer decrement is necessary for bringing the pointer to the first byte of data.

Nope. That's not how it works.

This is dangerous because using it in a language like C++ with it's dynamic memory allocation of containers based on their size and space needs could corrupt data at the point of return from read() function.

Nope. That's not how it works!

C and C++ are an explicit languages. Everything happens in plain sight and nothing happens without you (the programmer) explicitly requesting it. No memory is allocated without you requesting this to happen. It can either be an explicit , some RAII, automatic storage or the use of a container. But nothing happens "out of the blue" in C and C++. There's no built-in garbage collection^1 in C nor C++. Objects don't move around in memory or resize without you explicitly coding something into your program that makes this happen.


[1]: There are GC libraries you can use, but those never will stomp onto anything that can be reached by code that's executing. Essentially garbage collector libraries for C and C++ are memory leak detectors, which will free memory that can no longer be reached by normal program flow.

Sours: https://stackoverflow.com/questions/27074986/proper-way-to-use-gnu-linux-read-function

You will also like:

read(3) - Linux man page

Prolog

This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.

Name

pread, read - read from a file

Synopsis

#include <unistd.h>

ssize_t pread(intfildes, void *buf, size_tnbyte, off_toffset);
ssize_t read(int fildes, void *buf, size_tnbyte);

Description

The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf. The behavior of multiple concurrent reads on the same pipe, FIFO, or terminal device is unspecified.

Before any action described below is taken, and if nbyte is zero, the read() function may detect and return errors as described below. In the absence of errors, or if error detection is not performed, the read() function shall return zero and have no other results.

On files that support seeking (for example, a regular file), the read() shall start at a position in the file given by the file offset associated with fildes. The file offset shall be incremented by the number of bytes actually read.

Files that do not support seeking-for example, terminals-always read from the current position. The value of a file offset associated with such a file is undefined.

No data transfer shall occur past the current end-of-file. If the starting position is at or after the end-of-file, 0 shall be returned. If the file refers to a device special file, the result of subsequent read() requests is implementation-defined.

If the value of nbyte is greater than {SSIZE_MAX}, the result is implementation-defined.

When attempting to read from an empty pipe or FIFO:

*
If no process has the pipe open for writing, read() shall return 0 to indicate end-of-file.
*
If some process has the pipe open for writing and O_NONBLOCK is set, read() shall return -1 and set errno to [EAGAIN].
*
If some process has the pipe open for writing and O_NONBLOCK is clear, read() shall block the calling thread until some data is written or the pipe is closed by all processes that had the pipe open for writing.

When attempting to read a file (other than a pipe or FIFO) that supports non-blocking reads and has no data currently available:

*
If O_NONBLOCK is set, read() shall return -1 and set errno to [EAGAIN].
*
If O_NONBLOCK is clear, read() shall block the calling thread until some data becomes available.
*
The use of the O_NONBLOCK flag has no effect if there is some data available.

The read() function reads data previously written to a file. If any portion of a regular file prior to the end-of-file has not been written, read() shall return bytes with value 0. For example, lseek() allows the file offset to be set beyond the end of existing data in the file. If data is later written at this point, subsequent reads in the gap between the previous end of data and the newly written data shall return bytes with value 0 until data is written into the gap.

Upon successful completion, where nbyte is greater than 0, read() shall mark for update the st_atime field of the file, and shall return the number of bytes read. This number shall never be greater than nbyte. The value returned may be less than nbyte if the number of bytes left in the file is less than nbyte, if the read() request was interrupted by a signal, or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately available for reading. For example, a read() from a file associated with a terminal may return one typed line of data.

If a read() is interrupted by a signal before it reads any data, it shall return -1 with errno set to [EINTR].

If a read() is interrupted by a signal after it has successfully read some data, it shall return the number of bytes read.

For regular files, no data transfer shall occur past the offset maximum established in the open file description associated with fildes.

If fildes refers to a socket, read() shall be equivalent to recv() with no flags set.

If the O_DSYNC and O_RSYNC bits have been set, read I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion. If the O_SYNC and O_RSYNC bits have been set, read I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.

If fildes refers to a shared memory object, the result of the read() function is unspecified.

If fildes refers to a typed memory object, the result of the read() function is unspecified.

A read() from a STREAMS file can read data in three different modes: byte-stream mode, message-nondiscard mode, and message-discard mode. The default shall be byte-stream mode. This can be changed using the I_SRDOPT ioctl() request, and can be tested with I_GRDOPT ioctl(). In byte-stream mode, read() shall retrieve data from the STREAM until as many bytes as were requested are transferred, or until there is no more data to be retrieved. Byte-stream mode ignores message boundaries.

In STREAMS message-nondiscard mode, read() shall retrieve data until as many bytes as were requested are transferred, or until a message boundary is reached. If read() does not retrieve all the data in a message, the remaining data shall be left on the STREAM, and can be retrieved by the next read() call. Message-discard mode also retrieves data until as many bytes as were requested are transferred, or a message boundary is reached. However, unread data remaining in a message after the read() returns shall be discarded, and shall not be available for a subsequent read(), getmsg(), or getpmsg() call.

How read() handles zero-byte STREAMS messages is determined by the current read mode setting. In byte-stream mode, read() shall accept data until it has read nbyte bytes, or until there is no more data to read, or until a zero-byte message block is encountered. The read() function shall then return the number of bytes read, and place the zero-byte message back on the STREAM to be retrieved by the next read(), getmsg(), or getpmsg(). In message-nondiscard mode or message-discard mode, a zero-byte message shall return 0 and the message shall be removed from the STREAM. When a zero-byte message is read as the first message on a STREAM, the message shall be removed from the STREAM and 0 shall be returned, regardless of the read mode.

A read() from a STREAMS file shall return the data in the message at the front of the STREAM head read queue, regardless of the priority band of the message.

By default, STREAMs are in control-normal mode, in which a read() from a STREAMS file can only process messages that contain a data part but do not contain a control part. The read() shall fail if a message containing a control part is encountered at the STREAM head. This default action can be changed by placing the STREAM in either control-data mode or control-discard mode with the I_SRDOPT ioctl() command. In control-data mode, read() shall convert any control part to data and pass it to the application before passing any data part originally present in the same message. In control-discard mode, read() shall discard message control parts but return to the process any data part in the message.

In addition, read() shall fail if the STREAM head had processed an asynchronous error before the call. In this case, the value of errno shall not reflect the result of read(), but reflect the prior error. If a hangup occurs on the STREAM being read, read() shall continue to operate normally until the STREAM head read queue is empty. Thereafter, it shall return 0.

The pread() function shall be equivalent to read(), except that it shall read from a given position in the file without changing the file pointer. The first three arguments to pread() are the same as read() with the addition of a fourth argument offset for the desired position inside the file. An attempt to perform a pread() on a file that is incapable of seeking shall result in an error.

Return Value

Upon successful completion, read() and pread() shall return a non-negative integer indicating the number of bytes actually read. Otherwise, the functions shall return -1 and set errno to indicate the error.

Errors

The read() and pread() functions shall fail if:

EAGAIN
The O_NONBLOCK flag is set for the file descriptor and the process would be delayed.
EBADF
The fildes argument is not a valid file descriptor open for reading.
EBADMSG
The file is a STREAM file that is set to control-normal mode and the message waiting to be read includes a control part.
EINTR
The read operation was terminated due to the receipt of a signal, and no data was transferred.
EINVAL
The STREAM or multiplexer referenced by fildes is linked (directly or indirectly) downstream from a multiplexer.
EIO
The process is a member of a background process attempting to read from its controlling terminal, the process is ignoring or blocking the SIGTTIN signal, or the process group is orphaned. This error may also be generated for implementation-defined reasons.
EISDIR
The fildes argument refers to a directory and the implementation does not allow the directory to be read using read() or pread(). The readdir() function should be used instead.
EOVERFLOW
The file is a regular file, nbyte is greater than 0, the starting position is before the end-of-file, and the starting position is greater than or equal to the offset maximum established in the open file description associated with fildes.

The read() function shall fail if:

EAGAIN or EWOULDBLOCK

The file descriptor is for a socket, is marked O_NONBLOCK, and no data is waiting to be received.

ECONNRESET
A read was attempted on a socket and the connection was forcibly closed by its peer.
ENOTCONN
A read was attempted on a socket that is not connected.
ETIMEDOUT
A read was attempted on a socket and a transmission timeout occurred.

The read() and pread() functions may fail if:

EIO
A physical I/O error has occurred.
ENOBUFS
Insufficient resources were available in the system to perform the operation.
ENOMEM
Insufficient memory was available to fulfill the request.
ENXIO
A request was made of a nonexistent device, or the request was outside the capabilities of the device.

The pread() function shall fail, and the file pointer shall remain unchanged, if:

EINVAL
The offset argument is invalid. The value is negative.
EOVERFLOW
The file is a regular file and an attempt was made to read at or beyond the offset maximum associated with the file.
ENXIO
A request was outside the capabilities of the device.
ESPIPE
fildes is associated with a pipe or FIFO.

The following sections are informative.

Examples

Reading Data into a Buffer

The following example reads data from the file associated with the file descriptor fd into the buffer pointed to by buf.

#include <sys/types.h> #include <unistd.h> ... char buf[20]; size_t nbytes; ssize_t bytes_read; int fd; ... nbytes = sizeof(buf); bytes_read = read(fd, buf, nbytes); ...

Application Usage

None.

Rationale

This volume of IEEE Std 1003.1-2001 does not specify the value of the file offset after an error is returned; there are too many cases. For programming errors, such as [EBADF], the concept is meaningless since no file is involved. For errors that are detected immediately, such as [EAGAIN], clearly the pointer should not change. After an interrupt or hardware error, however, an updated value would be very useful and is the behavior of many implementations.

Note that a read() of zero bytes does not modify st_atime. A read() that requests more than zero bytes, but returns zero, shall modify st_atime.

Implementations are allowed, but not required, to perform error checking for read() requests of zero bytes.

Input and Output

The use of I/O with large byte counts has always presented problems. Ideas such as lread() and lwrite() (using and returning longs) were considered at one time. The current solution is to use abstract types on the ISO C standard function to read() and write(). The abstract types can be declared so that existing functions work, but can also be declared so that larger types can be represented in future implementations. It is presumed that whatever constraints limit the maximum range of size_t also limit portable I/O requests to the same range. This volume of IEEE Std 1003.1-2001 also limits the range further by requiring that the byte count be limited so that a signed return value remains meaningful. Since the return type is also a (signed) abstract type, the byte count can be defined by the implementation to be larger than an int can hold.

The standard developers considered adding atomicity requirements to a pipe or FIFO, but recognized that due to the nature of pipes and FIFOs there could be no guarantee of atomicity of reads of {PIPE_BUF} or any other size that would be an aid to applications portability.

This volume of IEEE Std 1003.1-2001 requires that no action be taken for read() or write() when nbyte is zero. This is not intended to take precedence over detection of errors (such as invalid buffer pointers or file descriptors). This is consistent with the rest of this volume of IEEE Std 1003.1-2001, but the phrasing here could be misread to require detection of the zero case before any other errors. A value of zero is to be considered a correct value, for which the semantics are a no-op.

I/O is intended to be atomic to ordinary files and pipes and FIFOs. Atomic means that all the bytes from a single operation that started out together end up together, without interleaving from other I/O operations. It is a known attribute of terminals that this is not honored, and terminals are explicitly (and implicitly permanently) excepted, making the behavior unspecified. The behavior for other device types is also left unspecified, but the wording is intended to imply that future standards might choose to specify atomicity (or not).

There were recommendations to add format parameters to read() and write() in order to handle networked transfers among heterogeneous file system and base hardware types. Such a facility may be required for support by the OSI presentation of layer services. However, it was determined that this should correspond with similar C-language facilities, and that is beyond the scope of this volume of IEEE Std 1003.1-2001. The concept was suggested to the developers of the ISO C standard for their consideration as a possible area for future work.

In 4.3 BSD, a read() or write() that is interrupted by a signal before transferring any data does not by default return an [EINTR] error, but is restarted. In 4.2 BSD, 4.3 BSD, and the Eighth Edition, there is an additional function, select(), whose purpose is to pause until specified activity (data to read, space to write, and so on) is detected on specified file descriptors. It is common in applications written for those systems for select() to be used before read() in situations (such as keyboard input) where interruption of I/O due to a signal is desired.

The issue of which files or file types are interruptible is considered an implementation design issue. This is often affected primarily by hardware and reliability issues.

There are no references to actions taken following an "unrecoverable error". It is considered beyond the scope of this volume of IEEE Std 1003.1-2001 to describe what happens in the case of hardware errors.

Previous versions of IEEE Std 1003.1-2001 allowed two very different behaviors with regard to the handling of interrupts. In order to minimize the resulting confusion, it was decided that IEEE Std 1003.1-2001 should support only one of these behaviors. Historical practice on AT&T-derived systems was to have read() and write() return -1 and set errno to [EINTR] when interrupted after some, but not all, of the data requested had been transferred. However, the U.S. Department of Commerce FIPS 151-1 and FIPS 151-2 require the historical BSD behavior, in which read() and write() return the number of bytes actually transferred before the interrupt. If -1 is returned when any data is transferred, it is difficult to recover from the error on a seekable device and impossible on a non-seekable device. Most new implementations support this behavior. The behavior required by IEEE Std 1003.1-2001 is to return the number of bytes transferred.

IEEE Std 1003.1-2001 does not specify when an implementation that buffers read()ss actually moves the data into the user-supplied buffer, so an implementation may chose to do this at the latest possible moment. Therefore, an interrupt arriving earlier may not cause read() to return a partial byte count, but rather to return -1 and set errno to [EINTR].

Consideration was also given to combining the two previous options, and setting errno to [EINTR] while returning a short count. However, not only is there no existing practice that implements this, it is also contradictory to the idea that when errno is set, the function responsible shall return -1.

Future Directions

None.

See Also

fcntl(), ioctl(), lseek(), open(), pipe(), readv(), the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <stropts.h>, <sys/uio.h>, <unistd.h>

Copyright

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright © 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html.

Referenced By

pth(3)
Sours: https://linux.die.net/man/3/read


4780 4781 4782 4783 4784