Great Deal! Get Instant $10 FREE in Account on First Order + 10% Cashback on Every Order Order Now

CSE 460 Lab 5: System Calls for I/0 Highlights of This Lab: Introduction to System Calls System Calls versus Library Routines Using System Calls for File I/0 perror() References Lab Exercise...

1 answer below »
CSE 460 Lab 5: System Calls for I/0
Highlights of This Lab:
Introduction to System Calls
System Calls versus Li
ary Routines
Using System Calls for File I/0
pe
or()
References
Lab Exercise
Introduction to System Calls
System calls are commands that are executed by the operating system. "System calls are the only way to access
kernel facilities such as file system, multitasking mechanisms and the interprocess communication primitives."
(Rochkind's book, Advanced Unix Programming)
Here is a short list of System Calls that we may be using in the labs:
For file I/0
creat(name, permissions)
open(name, mode)
close(fd)
ead(fd, buffer, num)
write(fd, buffer, num)
stat(name, buffer)
fstat(fd, buffer)
For process control
fork()
wait(status)
execl(), execlp(), execv(), execvp()
exit()
signal(sig, handler)
kill(sig, pid)
For interprocess communication
pipe(filedes)
System Calls versus Li
ary Routines
The tricky thing about system calls is that they look very much like a li
ary routine (or a regular function) that
you have already been using (for instance, printf). The only way to tell which is a li
ary routine and which is a
system call is to remember which is which.
Another way to obtain information about the system call is to refer to Section 2 of the man pages. For instance, to
find more about the "read" system call you could type:
$ man -s 2 read
By contrast, on our cu
ent version of Linux, if you try:
$ man -a read
Section 1 of the li
ary will be displayed (indicated by the 1 in parenthesis). To go the the next section, you can
use q followed by an enter key.
Section 3 contains li
ary routines. By issuing a:
$ man -s 3 fread
you will learn more about the fread li
ary routine.
Some li
ary functions have embedded system calls. For instance, the li
ary routines scanf and printf make use
of the system calls read and write. The relationship of li
ary functions and system calls is shown in the below
diagram (taken from John Shapley Gray's Interprocess Communications in UNIX)
"The a
ows in the diagram indicate possible paths of communication. As shown, executable programs may make
use of system calls directly to request the kernel to perform a specific function. Or, the executable program may
invoke a li
ary function which in turn may perform system calls." (page 4 and 5, Interprocess Communications
in UNIX).
Using System Calls for File I/O
The main systems calls that will be needed for this lab are
open()
close()
ead()
write()
stat()
fstat()
Each of these will be covered in their own subsection
open():
#include #include #include int open(const char *path, int flags [, mode_t mode ]);
path is a string that contains the name and location of the file to be opened.
The mode of the file to be opened is determined by the flags variable. It must have one of the following values:
O_RDONLY Read only mode
O_WRONLY Write only mode
O_RDWR Read/Write mode
and may have one or more options OR-ed on. A few examples of options include:
O_APPEND If the file exists, append to it.
O_CREAT If the file does not exist create it.
O_EXCL (Only with O_CREAT.) If the file already exists, open fails and returns an e
or.
O_TRUNC If the file exists and is being opened for writing, truncate it to length 0.
Upon success, open returns a file descriptor. If the operation fails, a -1 is returned. Use the 'man -S 2 open'
command for more information on this system call.
The convenience system call creat(const char *path, mode_t mode) is equivalent to open(path,
O_WRONLY|O_CREAT|O_TRUNC, mode). Use the 'man -S 2 creat' command for more information on this
command.
When you use the O_CREAT flag you are required to provide the mode argument to set access permissions for the
new file. The permissions you supply will be AND-ed against the complement of the user's umask. For example:
outFile = open("myfile", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
In the above example, the permissions set on "myfile" will be read and write by the user (S_IRUSR | S_IWUSR).
For more details on these modes or permissions see man -S 2 open.
close():
#include int close(int filedes);
close() closes the file indicated by the file descriptor filedes.
The operating system will free any resources allocated to the file during its operation. Use the 'man -S 2 close'
command for more information on this system call.
ead():
#include ssize_t read(int filedes, void *buf, size_t nbyte);
ead() attempts to read nbyte bytes from the file associated with filedes into the buffer pointed to by buf.
If nbyte is zero, read returns zero and has no other results. On success a non-negative integer is returned
indicating the number of bytes actually read. Otherwise, a -1 is returned. Use the man -S 2 read command fo
more information on this system call.
write():
#include < unistd.h
ssize_t write(int filedes, const void *buf, size_t nbyte);
write() attempts to write nbyte bytes from the buffer pointed to by buf to the file associated with filedes.
If nbyte is zero and the file is a regular file, write returns zero and has no other results. On success, write returns
the number of bytes actually written. Otherwise, it returns -1. Use the command 'man -S 2 write' for more
information on this system call.
The following is a sample program reads a file and displays its contents on the screen.
Modified from page 7 of Interprocess Communication in Unix by John
Shapely Gray
readfile.cpp
Usage: a.out filename
Displays the contents of filename
#include #include #include #include
needed for open
#include
needed for open
#include
needed for open
using namespace std;
int main (int argc, char *argv[])
{
int inFile;
int n_char = 0;
char buffer[10];
inFile = open(argv[1], O_RDONLY);
if (inFile == -1)
{
XXXXXXXXXXexit(1);
}

Use the read system call to obtain 10 characters from inFile
while((n_char = read(inFile, buffer, 10)) != 0)
{

Display the characters read
XXXXXXXXXXn_char = write(1, buffer, n_char);
}
close (inFile);
return 0;
}
You will notice that the first argument to a read/write system call is an integer value indicating the file descriptor.
When a program executes, the operating system will automatically open three file descriptors:
0 stdin --standard input (defaults to the keyboard)
1 stdout --standard output (defaults to the terminal)
2 stde
--standard e
or (defaults to the console device)
A write to file descriptor 1 (as in the above code) will be writing to your terminal.
stat():
#include < sys/types.h
#include < sys/stat.h
int stat(const char *path, struct stat *buf)
stat() obtains information about the named file, and puts them in the stat structure.
This command comes in handy if you want to emulate the ls command. All the information that you need to know
about a file is given in the stat structure.
The stat structure is defined as:
mode_t st_mode; /* protection *
ino_t st_ino; /* this file's number *
dev_t st_dev; /* device file resides on *
dev_t st_rdev; /* device identifier (special files only) *
nlink_t st_nlink; /* number of hard links to the file*
uid_t st_uid; /* user ID of owner *
gid_t st_gid; /* group ID of owner *
off_t st_size; /* file size in bytes *
time_t st_atime; /* time of last access *
time_t st_mtime; /* time of last data modification *
time_t st_ctime; /* time of last file status change*
lksize_t st_blksize; /* prefe
ed I/O block size *
lkcnt_t st_blocks; /* number 512 byte blocks allocated *
Use the 'man -S 2 stat' command for more information on this system call.
fstat():
#include #include int fstat(int filedes, struct stat *buf)
fstat() is like stat(), but works on a file that is specified by the filedes file descriptor. Use the 'man -S 2 fstat'
command for more information on the fstat system call.
Example
#include #include #include #include
needed for open
#include
needed for open
#include
needed for open
using namespace std;
int main (int argc, char *argv[])
{
struct stat statBuf;
int e
, FD;
FD = open("openclose.in", O_WRONLY | O_CREAT, S_IREAD | S_IWRITE);

if(FD == -1) /* open failed? *
exit(-1);
e
= fstat(FD, &statBuf);
if(e
== -1) /* fstat failed? *
exit(-1);
printf("The number of blocks = %d\n", statBuf.st_blocks);

return 0;
}
pe
or()
In most cases, if a system call or li
ary function fails, it returns a value of -1 and assigns a value to an external
variable called e
no. This value indicates where the actual problem occu
ed.
It is a good programming habit to examine the return value from a system call or li
ary function to determine if
something went wrong. If there was a failure, the program should do something such as display a short e
o
message and exit (terminate) the program. The li
ary function pe
or can be used to produce an e
or message.
The following is an example of using pe
or to provide some e
or checking:
Modified from page 7 of Interprocess Communication in Unix by John
Shapely Gray
pe
or.cpp
checking e
no and using pe
o
#include #include #include #include no.h>
must use for pe
o
using namespace std;
extern int e
no;
in linux, don't seem to need this
int main (int argc, char *argv[])
{
XXXXXXXXXXint n_char=0;
char buffer[10];

Initially n_char is set to 0 -- e
no is 0 by default
XXXXXXXXXXprintf("n_char = %d \t e
no = %d\n", n_char, e
no);

Display a prompt to stdout
XXXXXXXXXXn_char = write(1, "Enter a word ", 14);

Use the read system call to obtain 10 characters from stdin
XXXXXXXXXXn_char = read(0, buffer, 10);
XXXXXXXXXXprintf("\nn_char = %d \t e
no = %d\n", n_char, e
no);

If read has failed
XXXXXXXXXXif (n_char ==
Answered Same Day Jun 03, 2021

Solution

Shivani answered on Jun 03 2021
131 Votes
#include #include #include #include #include no.h
#include
needed for open
#include
needed for open
#include
needed for open
using namespace std;
int main(int argc, char *argv[])
{
    pid_t child_pid, wpid;
    int status = 0;
    int FD, n_char=0;
    char buffer[100];
    
    printf("\n In Parent process now.");
    
Checking if the number of command-line arguments is 2
    if(argc != 2)
    {
        printf("\n Wrong number of command line arguments.");
        printf("\nUSAGE: myIO ");
        exit(-1);
    }
    
Forking a child process
    if ((child_pid = fork()) == 0)
    {
        
child...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here