If a Io System Call (E.g. Read) Returns -1 and Error Is Einter, How Should We Interpret This?

Of import Terminology

What is the File Descriptor?
File descriptor is integer that uniquely identifies an open up file of the process.

File Descriptor table: File descriptor tabular array is the collection of integer assortment indices that are file descriptors in which elements are pointers to file tabular array entries. One unique file descriptors table is provided in operating system for each procedure.

File Table Entry: File tabular array entries is a construction In-memory surrogate for an open file, which is created when process request to opens file and these entries maintains file position.

Standard File Descriptors: When any process starts, so that process file descriptors table's fd(file descriptor) 0, one, 2 open up automatically, (By default) each of these 3 fd references file table entry for a file named /dev/tty

/dev/tty: In-retentiveness surrogate for the terminal
Last: Combination keyboard/video screen

Read from stdin => read from fd 0 : Whenever we write any graphic symbol from keyboard, it read from stdin through fd 0 and save to file named /dev/tty.
Write to stdout => write to fd i : Whenever we come across any output to the video screen, information technology's from the file named /dev/tty and written to stdout in screen through fd i.
Write to stderr => write to fd ii : We see any fault to the video screen, it is also from that file write to stderr in screen through fd 2.

I/O Arrangement calls

Basically there are total v types of I/O organization calls:

1. Create: Used to Create a new empty file.

          Syntax in C language:                    int create(char *filename, mode_t manner)

Parameter:

  • filename : name of the file which you want to create
  • mode : indicates permissions of new file.

Returns:

  • return get-go unused file descriptor (by and large 3 when outset create use in procedure because 0, 1, 2 fd are reserved)
  • return -one when fault

How information technology work in OS

  • Create new empty file on disk
  • Create file table entry
  • Gear up kickoff unused file descriptor to point to file table entry
  • Return file descriptor used, -1 upon failure

two. open: Used to Open up the file for reading, writing or both.

          Syntax in C language                    #include<sys/types.h> #include<sys/stat.h> #include <fcntl.h>   int open (const char* Path, int flags [, int mode ]);        

Parameters

  • Path: path to file which you want to use
    • use absolute path begin with "/", when y'all are not piece of work in same directory of file.
    • Use relative path which is only file name with extension, when you lot are piece of work in aforementioned directory of file.
  • flags : How y'all like to use
    • O_RDONLY: read simply, O_WRONLY: write only, O_RDWR: read and write, O_CREAT: create file if it doesn't exist, O_EXCL: prevent cosmos if it already exists

How it works in OS

  • Find the existing file on deejay
  • Create file table entry
  • Set first unused file descriptor to signal to file table entry
  • Return file descriptor used, -1 upon failure

C

#include<stdio.h>

#include<fcntl.h>

#include<errno.h>

extern int errno ;

int primary()

{

int fd = open( "foo.txt" , O_RDONLY | O_CREAT);

printf ( "fd = %d/due north" , fd);

if (fd ==-1)

{

printf ( "Fault Number % d\north" , errno );

perror ( "Program" );

}

return 0;

}

Output:

fd = 3

3. shut: Tells the operating system you are done with a file descriptor and Shut the file which pointed by fd.

          Syntax in C language          #include <fcntl.h> int close(int fd);        

Parameter:

  • fd :file descriptor

Return:

  • 0 on success.
  • -1 on error.

How it works in the Bone

  • Destroy file table entry referenced by element fd of file descriptor table
    – As long as no other process is pointing to it!
  • Set element fd of file descriptor table to NULL

C

#include<stdio.h>

#include <fcntl.h>

int principal()

{

int fd1 = open up( "foo.txt" , O_RDONLY);

if (fd1 < 0)

{

perror ( "c1" );

leave (ane);

}

printf ( "opened the fd = % d\n" , fd1);

if (shut(fd1) < 0)

{

perror ( "c1" );

exit (1);

}

printf ( "closed the fd.\north" );

}

Output:

opened the fd = three closed the fd.

C

#include<stdio.h>

#include<fcntl.h>

int main()

{

int fd1 = open( "foo.txt" , O_RDONLY, 0);

close(fd1);

int fd2 = open up( "baz.txt" , O_RDONLY, 0);

printf ( "fd2 = % d\northward" , fd2);

get out (0);

}

Output:

fd2 = 3

Here, In this code first open() returns iii considering when master process created, then fd 0, 1, 2 are already taken by stdin, stdout and stderr. So kickoff unused file descriptor is iii in file descriptor table. Subsequently that in shut() arrangement call is free information technology this 3 file descriptor and so after ready 3 file descriptor as null. So when nosotros called 2nd open(), then outset unused fd is too 3. And then, output of this program is three.

4. read: From the file indicated by the file descriptor fd, the read() function reads cnt bytes of input into the memory expanse indicated by buf. A successful read() updates the admission time for the file.

          Syntax in C language                    size_t read (int fd, void* buf, size_t cnt);        

Parameters:

  • fd: file descriptor
  • buf: buffer to read data from
  • cnt: length of buffer

Returns: How many bytes were actually read

  • return Number of bytes read on success
  • return 0 on reaching terminate of file
  • render -one on error
  • render -1 on betoken interrupt

Important points

  • buf needs to point to a valid retention location with length not smaller than the specified size because of overflow.
  • fd should exist a valid file descriptor returned from open() to perform read operation considering if fd is NULL and so read should generate error.
  • cnt is the requested number of bytes read, while the render value is the bodily number of bytes read. Also, some times read system telephone call should read less bytes than cnt.

C

#include<stdio.h>

#include <fcntl.h>

int principal()

{

int fd, sz;

char *c = ( char *) calloc (100, sizeof ( char ));

fd = open up( "foo.txt" , O_RDONLY);

if (fd < 0) { perror ( "r1" ); go out (1); }

sz = read(fd, c, 10);

printf ( "called read(% d, c, x). returned that"

" %d bytes were read.\n" , fd, sz);

c[sz] = '\0' ;

printf ( "Those bytes are as follows: % s\due north" , c);

}

Output:

called read(three, c, 10).  returned that 10 bytes  were read. Those bytes are as follows: 0 0 0 foo.

Suppose that foobar.txt consists of the 6 ASCII characters "foobar". Then what is the output of the following program?

C

#include<stdio.h>

#include<unistd.h>

#include<fcntl.h>

#include<stdlib.h>

int master()

{

char c;

int fd1 = open( "sample.txt" , O_RDONLY, 0);

int fd2 = open( "sample.txt" , O_RDONLY, 0);

read(fd1, &c, 1);

read(fd2, &c, 1);

printf ( "c = %c\north" , c);

exit (0);

}

Output:

c = f

The descriptors fd1 and fd2 each take their own open file table entry, so each descriptor has its own file position for foobar.txt . Thus, the read from fd2 reads the kickoff byte of foobar.txt , and the output is c = f, non c = o.

5. write: Writes cnt bytes from buf to the file or socket associated with fd. cnt should non be greater than INT_MAX (divers in the limits.h header file). If cnt is zero, write() but returns 0 without attempting any other action.

#include <fcntl.h> size_t write (int fd, void* buf, size_t cnt);        

Parameters:

  • fd: file descriptor
  • buf: buffer to write data to
  • cnt: length of buffer

Returns: How many bytes were actually written

  • return Number of bytes written on success
  • return 0 on reaching end of file
  • return -one on fault
  • render -one on signal interrupt

Of import points

  • The file needs to be opened for write operations
  • buf needs to exist at least as long as specified by cnt because if buf size less than the cnt then buf will lead to the overflow condition.
  • cnt is the requested number of bytes to write, while the return value is the actual number of bytes written. This happens when fd take a less number of bytes to write than cnt.
  • If write() is interrupted by a point, the effect is one of the following:
    -If write() has not written whatever data all the same, it returns -1 and sets errno to EINTR.
    -If write() has successfully written some data, information technology returns the number of bytes it wrote before it was interrupted.

C

#include<stdio.h>

#include <fcntl.h>

main()

{

int sz;

int fd = open up( "foo.txt" , O_WRONLY | O_CREAT | O_TRUNC, 0644);

if (fd < 0)

{

perror ( "r1" );

go out (1);

}

sz = write(fd, "hello geeks\n" , strlen ( "hello geeks\n" ));

printf ( "chosen write(% d, \"how-do-you-do geeks\\due north\", %d)."

" Information technology returned %d\n" , fd, strlen ( "hello geeks\north" ), sz);

shut(fd);

}

Output:

called write(iii, "howdy geeks\due north", 12).  it returned 11

Here, when you see in the file foo.txt after running the lawmaking, you become a "how-do-you-do geeks". If foo.txt file already accept some content in it and so write organization call overwrite the content and all previous content are deleted and just "hello geeks" content will accept in the file.

Print "hello globe" from the program without use any printf or cout function.

C

#include<stdio.h>

#include<string.h>

#include<unistd.h>

#include<fcntl.h>

int primary ( void )

{

int fd[two];

char buf1[12] = "hi earth" ;

char buf2[12];

fd[0] = open up( "foobar.txt" , O_RDWR);

fd[1] = open( "foobar.txt" , O_RDWR);

write(fd[0], buf1, strlen (buf1));

write(ane, buf2, read(fd[1], buf2, 12));

close(fd[0]);

close(fd[one]);

return 0;

}

Output:

hullo globe

In this code, buf1 array'south string "hello world" is first write in to stdin fd[0] then subsequently that this string write into stdin to buf2 assortment. Later that write into buf2 array to the stdout and print output " hullo world ".
This article is contributed by Kadam Patel. If you like GeeksforGeeks and would like to contribute, you tin also write an commodity using write.geeksforgeeks.org or mail service your article to review-team@geeksforgeeks.org. Encounter your article appearing on the GeeksforGeeks main page and assist other Geeks.
Please write comments if you find anything wrong, or you want to share more than information about the topic discussed higher up.


georgefoldente.blogspot.com

Source: https://www.geeksforgeeks.org/input-output-system-calls-c-create-open-close-read-write/

0 Response to "If a Io System Call (E.g. Read) Returns -1 and Error Is Einter, How Should We Interpret This?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel