Is the 'read' unix system call interface goofed up?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sgurukrupagmailcom
    New Member
    • Apr 2008
    • 14

    Is the 'read' unix system call interface goofed up?

    Hi,

    The prototype for the 'read' system call as given in the POSIX standard reads like this:

    Code:
    #include <unistd.h>
    
    ssize_t read(int filedes, void* buf, size_t nbytes);
    This system call returns the number of bytes read from the file associated with the file descriptor 'filedes'.

    The odd thing about it is that we need to specify the number of bytes to be read using an unsigned integer, but the return type is a signed integer. The range of the unsigned integer is twice that of the signed integer. If we do assume that the integer data type on a particular machine is 1 byte long then, the unsigned integer would be ranging from 0 to 255 whereas the signed integer would be ranging from -128 to 127. If I have the following code snippet:

    Code:
    unsigned char buf[128];
    int i = read(fd, buf, 128); /* 'fd' specifies a file descriptor */
    what would be the value of 'i' after the code snippet executes, the size of the 'integer' data type being 1 byte? I couldn't get the answer in the man pages. Could we conclude that the interface for 'read' system call is faulty?
  • experte
    New Member
    • Jun 2010
    • 1

    #2
    Originally posted by sgurukrupagmail com
    I couldn't get the answer in the man pages.
    The man page (read(2) on linux) says:
    Code:
    #include <unistd.h>
    ssize_t read(int fd, void *buf, size_t count);
    ...
    If count is greater than SSIZE_MAX, the result is unspecified.
    This should answer your question: if you want to rely on the result, make sure you never ask for more than SSIZE_MAX bytes.

    Comment

    • sgurukrupagmailcom
      New Member
      • Apr 2008
      • 14

      #3
      Thanks. How did I miss that sentence in the man pages?
      :-)

      Comment

      Working...