You are on page 1of 66

System calls

A system call is just what its name implies -- a request for the

operating system to do something on behalf of the user's program.


To use the services in the OS,Unix offers some special functions
known as system calls. The system call is a task which performs
very basic functions that requires communication with CPU,

memory and other devices.


The system calls are functions used in the kernel itself. To the
programmer, the system call appears as a normal C function call.
UNIX system calls are used to manage the file system, control

processes, and to provide inter process communication.


L1.1

File Structure Related System Calls


The file structure related system calls available in the UNIX system
let you create, open, and close files, read and write files, randomly
access files and remove files, get information about files, check the
accessibility of files, change protections, owner, and group of files,

and control devices.


All input and output operations start by opening a file using either
the "creat()" or "open()" system calls.

File descriptors

Each UNIX process has 20 file descriptors at it disposal, numbered 0 to 19.

The first three are already opened when the process begins
0: The standard input

1: The standard output


2: The standard error output

When the parent process forks a process, the child process inherits the file
descriptors of the parent.

Returns: file descriptor if OK, -1 on error.

Introduction
- In order to make use of services such as application programs file
creation,process duplication, and interprocess communication,must talk
to the operating system.
- a collection of routines called system calls,which are the programmers
functional interface to the UNIX kernel.
- The UNIX system calls can be loosely grouped into three main categories:
file management
process management
error handling

File-management system calls hierarchy

Files

open

close

chmod

fcntl

read
fstat

write
ftruncate

mknod

ioctl

lseek

unlink

truncate

stat

chown
sync

dup

gethostname

htonl

special

Directory

link

pipe

Sockets

Internet sockets

gethostbyname

dup2

htons
7

accept

bind

inet_addr

connect

inet_ntoa

getdents

listen

socket

KERNEL BASICS

- The UNIX kernel


the part of the UNIX operating system that contains the code for:
sharing the CPU and RAM between competing processes
processing all system calls
handling peripherals
- The kernel is a program that is loaded from disk into RAM
when the computer is first tuned on.
- Kernel Subsystems
Memory management
Process management
Interprocess communication(IPC)
Input/output
File management
- It always stays in RAM.
and it runs until the system is turned off or crashes.

- User programs make use of the kernel via the system call interface.
8

- A typical sequence of events:

int fd; /* File descriptor */

fd = open( fileName, ); /* Open file, return file descriptor */


if ( fd==-1 ) { /* Deal with error condition */ }

fcntl( fd, ); /* Set some I/O flags if necessary */

read( fd, ); /* Read from file */

write( fd, ); /* Write to file */

lseek( fd, ); /* Seek within file */

close(fd); /* Close the file, freeing file descriptor */

- When a process no longer needs to access an open file,


it should close it using the close system call.
- All of a process open files are automatically closed
when the process terminates.
but, its better programming practice to explicitly close your files.
- File descriptors are numbered sequentially, starting from zero.
By convention,
the first three file descriptor values have a special meaning:
Value

Meaning

0
1
2

standard input
standard output
standard error
10

- For Example,
the printf() library function always sends its output
using file descriptor 1.
the scanf() always reads its input using file descriptor 0.

Fd0
i/p
Fd1
o/p
Fd2
error

File
Many file descriptors, one file

11

Low Level File Access


System call

Description

open()

Opens the file

create()

Create files with specified mode

read()

Read the content from the file and places it into buffers

write()

Writes the content in buffers to the file

close()

Closes the file

lseek()

Access the content in the file randomly

stat() and fstat()

Query the file attributes

ioctl()

Access the devices files

dup(),dup2()

Create the duplicate I/O channel with same name

umask()

Set the default permissions to the file

Types of system calls in UNIX:


1.Open

2.create 3.read 4.write

5.Close

6.lseek

9.ioctl

10.umask 11.dup 12.dup2

7.stat

8.fstat

L1.2

13

Opening a File: open()

open(filename , flags , mode)


open() allows you to open or create a file for reading and/or writing.
System Call: int open( const char* fileName, int O_flags,mode)
fileName : an absolute or relative pathname,
O_flags : a bitwise oring of a read/write flag together with zero or
more miscellaneous flags.
mode permission : a number that encodes the value of the files
permission flags.
If file opens returns positive integer filedescriptor otherwise it returns -1
Eg1:

int fd;
fd=open(hi.txt,O_CREAT | O_RDWR,0600);

2: int fd ;
fd=open(hello.txt,O_RDWR,0600);
14

- The read/write flags are as follows:


FLAG
O_RDONLY
O_WRONLY
O_RDWR

MEANING
Open for read only.
Open for write only.
Open for both read and write.

- The miscellaneous flags are as follows:


FLAG
O_APPEND

MEANING
Position the file pointer at the end of the file
before each write().

O_CREAT

If the file doesnt exist, create the file and


set the owner ID to the process effective UID.

O_EXCL

If O_CREAT is set and the file exists,


then open() fails.

O_TRUNC

If the file exists, it is truncated to length zero.


15

Creating

a File

- To create a file, use the O_CREAT flags as part of the mode flags and
supply the initial file-permission flag settings as an octal value.

System call :int create(filename , mode)


fileName : an absolute or relative pathname,

mode permission : a number that encodes the value of the files


permission flags.
Eg:
create(m.txt,0600);

int fd;
fd = open( filename, O_CREAT | O_RDWR, 0600);
16

- Reading From a File : read()


To read bytes from a file, it uses the read() system call,
System Call: ssize_t read( int fd, void* buf, int size)
fd is the file descriptor of the file that is returned from the open or
create system calls.
*buf -> it is a pointer pointing to the memory location where the
data read from the file will be stored.
Size specifies the num of bytes that are actually read from the file.
Returns
- Number of bytes read
- Value of 0 if nothing more to read
- Value of -1 if an error
Eg:
this code reads upto 1024 bytes from file m.txt
int fd=open(m.txt,O_RDONLY);
void *buf=(char *)malloc(1024);
17
read(fd,buf,10);

- Writing to a File: write()


To write bytes to a file, it uses the write() system call,
which works as follows:
System Call: ssize_t write( int fd, void* buf, int size)
fd is the file descriptor of the file that is returned from the open or
create system calls.
*buf -> it is a pointer pointing to the memory location where the
data read from the file will be stored.
Size specifies the num of bytes that are actually read from the file.
If successful, write() returns the number of bytes that were
written; otherwise, it returns a value of -1.
Eg:

int fd=open(m.txt,O_RDWR);
write(fd,HELLO WORLD,10);
18

- Moving in a File : lseek()


System Call: int lseek( int fd, off_t offset, int location)
lseek() allows you to change a descriptors current file position.
fd : the file descriptor,
offset(space) : this represents the num of bytes that we want the file
descriptor to move from the position repreented by location.
Location: how offset should be interpreted.

- The three possible values of location


VALUE

MEANING

SEEK_SET
SEEK_CUR
SEEK_END

offset is relative to the start of the file.


offset is relative to the current file position.
offset is relative
to the end of the file.
19

Closing a File: close()


- uses the close() system call to free the file descriptor of the input.
System Call : int close(int fd)
close() frees the file descriptor fd.
If successful, close() returns a value of 0;
otherwise, it returns a value of -1.

Eg:

close(fd); /* Close input file */

20

EG1:/* program using open(),write(),lseek(),close() systemcalls

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

main()
{

int fd;
fd = open(hi.txt, O_CREAT | O_RDWR, 0600 );
write( fd, HELLOWORLD!, 6);

lseek( fd,0, SEEK_SET );


write( fd, UNIXLAB, 2 );
close(fd);
}
Output : vi hi.txt

UNLLOW
21

*/

EG2:/* program using open(),write(),lseek(),close() and read() systemcalls

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

main()
{

int fd1,fd2;
char buf[1024];
long int n;

fd1 = open(h1.txt, O_CREAT | O_RDONLY, 0600 );


fd2 = open(h2.txt, O_CREAT | O_WRONLY, 0600 );
lseek( fd,10, SEEK_SET );
n=read(fd1,buf,n);
close(fd1);

close(fd2);
}

22

*/

File Status
The i-node data structure holds all the information about a file
except the file's name and its contents.
Sometimes your programs need to use the information in the i-node
structure to do some job. You can access this information with the
stat() and fstat() system calls.

Obtaining File Information: stat(), and fstat()


stat(filename , buf)
fstat(fd , buf)

System Call : int stat( const char* path, struct stat* buf );
int fstat( int fd, struct stat* buf ) ;
path : represents the name and the relative or absolute path of file.
stat() fills the buffer buf with information about the file name.
The stat structure is defined in /usr/include/sys/stat.h.

fstat() performs the same function as stat(), except that it takes


the file descriptor of the file to be stat end as its first parameter.

24

/* program using stat() and fstat() systemcalls */


#include <sys/types.h>
#include <sys/stat.h>
struct stat statusbuf
{
statusbuf.st_dev;
//device on which the file resides
statusbuf.st_ino;
//inode num of file
statusbuf.st_mode;
//file permission and file type info
statusbuf .st_nlink;
//the count of hard links to the file
statusbuf .st_uid;
//user id of file owner
statusbuf .st_gid;
//group id of file owner
statusbuf .st_size;
//file size
statusbuf .st_atime;
//the time the file was last accessed
statusbuf .st_mtime;
//the time the file was last modified
statusbuf .st_ctime;
//the time the status of file last changed
permission-owner,group,others
statusbuf .st_blocks;
//number of blocks of size 512bytes
that have been allocated
};

stat() and fstat() system calls


#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
main()
{
struct stat statusbuf;
int fd;
fd = open(hi.txt, O_RDWR, 0600 ); // hi.txt is existing file->123abcd
printf(fstat output);
fstat(fd, &statusbuf);
printf(stat output);
stat(hi.txt,&statusbuf);
printf(inode number %d,statusbuf.st_ino);
printf(file size %d,statusbuf.st_size);
close(fd);
}

Output :
Cat hi.txt
abcd
Space

Fstat output
Stat output
Inode number :160000000
File size: 11

ioctl Function:

It performs a variety of control functions on specified devices.


System call : int ioctl(fd , command , arguments)
Returns: -1 on error, something else if OK.
The function represented by cmd is applied on the device whose file
descriptor is provided.
arg is optional and represents the arguments for the function cmd.

28

umask Function:
The umask function sets the file mode creation mask for the process and
returns the previous value.
#include <sys/stat.h>
Syntax: mode_t umask(mode_t newmask);
Returns: previous file mode creation mask.
The newmask argument is formed as the bitwise OR of any of the nine
constants like S_IRUSR, S_IWUSR, and so on.

29

Eg:

o/p:

#include<stdio.h>
main()
{
int fd;
fd=open(m.txt,O_CREAT|O_RDWR,0777);
umask(0002);
close(fd);
}
ls l m.txt
-rwx-rwx-r-x

dup and dup2 System calls:


An existing file descriptor is duplicated by either of the following functions.
Syntax: int dup(int filedes);
int dup2(int filedes, int filedes2);
Both return: new file descriptor if OK,-1 on error.
The new file descriptor returned by dup is guaranteed to be the lowest-numbered
available file descriptor.
/* program using dup() and dup2() systemcalls */
Eg:
#include<stdio.h>
main()
{
int fd1,fd2;
fd1=open(m.txt,O_CREAT|O_RDWR,0600);
write(fd1,space,5);
fd2=dup(fd1);
(or)
dup2(fd1,fd2);
write(fd2,jet,3);
}
o/p:
vi m.txt
spacejet
31

Standard I/O functions


Function

Description

fopen()

Open the file for read/write purpose

fclose()

Open stream is closed by close function

fflush()

Buffering provided by the standard I/O is to use the minimum


number of read and write calls

gets() and fgets()

gets() reads from standard input until it reads the new line
character end-of-file
fgets() reads characters from stream and stores them into the
buffer pointed.

fseek()

Sets the file position indicator for the stream pointed by stream

getc(), fgetc(),
getchar()

getc() reads the one character at a time, implemented in macto


fgetc() reads the next character from file stream
getchar() reads the character from standard input

putc(), fputc(),
putchar()

putc() takes the character argument, and outputs it to the


specified file, implemented in macro
fputc() takes the character argument, and outputs it to the
specified file, not implemented in macro
putchar() takes the character and prints in stdout

Standard I/O functions


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.

fopen()
fclose()
fflush()
fseek()
fgetc()
getc()
fgets()
gets()
getchar()
putchar()
fputc()
putc()

Standard I/O
The fopen function opens a specified file.

Syntax:
FILE *fopen(const char *filename, const char *restrict type);
Filename:it opens the file named by the filename parameter in
specified mode.
Eg :

FILE *fp;
fp=fopen(m.txt,r);

Mode

Description

Open an existing file for reading

r+

Open existing file for both reading and writing

Open a file for writing. If the file already exists its content will be
wiped out. Otherwise afresh file is created for writing.

w+

Open a file for writing and reading. If the file already exists its
content will be wiped out. Otherwise afresh file is created for
writing.

Open a file for appending.

a+

Open a file for appending and reading.

fclose:
An open stream is closed by calling fclose.
Syntax: int fclose(FILE *fp);

Returns: 0 if OK, EOF on error.

Input Functions(Reading Characters)


Three functions allow us to read one character at a time.
getc:
fgetc:
getchar:

int getc (FILE *fp);


int fgetc (FILE *fp);
int getchar (void);

All three return: next character if OK, EOF on end of file or error.
The function getchar is equivalent to getc(stdin). getc can be
implemented as a macro, whereas fgetc cannot be implemented as a
macro.

Output Functions(Writing Characters)


Output function that corresponds to each of the input functions are:
putc:
fputc:
Putchar:

int putc (int c, FILE *fp);


int fputc (int c, FILE *fp);
int putchar (int c);

All three return: c if OK, EOF on error.


Like the input functions, putchar(c) is equivalent to putc(c, stdout),
and putc can be implemented as a macro, whereas fputc cannot be
implemented as a macro.

/* program using fopen(),fgetc(),fputc(),fclose() systemcalls


Eg:

#include<stdio.h>
main()
{
char c;
FILE *fp1,*fp2;
fp1=fopen(f1.txt,r);
fp2=fopen(f2.txt,w);
while((c=fgetc(fp1))!=EOF)
fputc(c,fp2);
fclose(fp1);
fclose(fp2);
}

o/p:

cat f1.txt
hello2014
cat f2.txt
hello2014

*/

/* program using getchar() and putchar() systemcalls

*/

Eg:

#include<stdio.h>
main()
{
int c;
while((c=getchar())!=EOF)
putchar(toupperc);
}

Eg2:

#include<stdio.h>
main()
{
int c;
c=getchar();
putchar(c);
}

o/p:

$./a.out
hello2014
HELLO2014

o/p:

$/a.out
hello
h

Line-at-a-Time I/O:
fgets:
gets:

char *fgets (char *restrict buf, int n, FILE *restrict fp);


char *gets(char *buf);

Both return: buf if OK, NULL on end of file or error.


Both specify the address of the buffer to read the line into. The
gets function reads from standard input, whereas fgets reads from the
specified stream.
With fgets, we have to specify the size of the buffer, n. This
function reads up through and including the next newline, but no more
than n1 characters, into the buffer. The buffer is terminated with a null
byte.

/* program using fgets(),puts() systemcalls


Eg:

#include<stdio.h>
main()
{
char c[100];
FILE *fp;
fp=fopen(m.txt,r);
if((fgets(c,5,fp)!=NULL)
puts(c);
fclose(c);
}

o/p:

$./a.out
$ cat m.txt
hello2014
HELL\O-nullchar

*/

fflush:
The C library function fflush,flushes the output buffer of a stream.
Syntax: int fflush(FILE *stream)
stream -- This is the pointer to a FILE object that specifies a
buffered stream.
Any buffered output data is flushed before the file is closed. Any
input data that may be buffered is discarded. If the standard I/O
library had automatically allocated a buffer for the stream, that
buffer is released.
This function returns zero value on success. If an error occurs, EOF
is returned and the error indicator is set(i.e. feof).
Eg: fflush(fp);
fflush(stdin);
fflush(stdout);

Fseek :
It is equivalent to lseek system call
Sets the file pointer position at the given offset from the whence
location in the file.
Syntax : int fseek(FILE *stream,long int offset,int whence);

stream represents the file


offset represents the number of bytes from whence
whence refers to the location related to offset has to be set,i.e.;
Location : SEEK_SET
SEEK_CUR
SEEK_END

/* program using fseek(),puts() systemcalls


Eg:
#include<stdio.h>

o/p:

main()
{
FILE *fp;
fp=fopen(m.txt,r+);
puts(hello,fp);
fseek(fp,0,SEEK_END);
puts(2014,fp);
fcolse(fp);
}
vi m.txt
//existing file
hello2014

*/

DIRECTORIES MAINTAINANCE

1.
2.
3.
4.
5.
6.
7.
8.

Directory functions are declared in a header file.


They use structure, DIR as a basis for directory manipulations.
A pointer to this structure called a directory stream(a DIR *).
A directory contains structures of type direct, defined in the include
file /usr/include/sys/ndir.h
chmod()
chown()
chdir()
link()
symlink()
mkdir()
rmdir()
getcwd()

link()
The UNIX system file structure allows more than one named
reference to a given file, a feature called "aliasing". all names of the
file refer to the same data.
Link() systemcall refers to hard link.
Syntax: int link(const char *filename1,const char *filename2);
or
int link(original_name, alias_name)

Filename1=original_name
Filename2=alias_name;
If the original file is deleted,the alias file can still be used to show the
content of the original file.

link() will fail and no link will be created if any of the following
conditions holds:
a path name component does not exist.
original_name does not exist.
alias_name does exist.
original_name is a directory and you are not the superuser.
a link is attempted across file systems.
The destination directory for alias_name is not writable.
The destination directory is on a mounted read-only file system.

Eg:

o/p:

#include <stdio.h>
main()
{
link(oldfile", newfile);
}
$cat oldfile
hello world
$cat newfile
helloworld

symlink()
Symlink() systemcall refers to softlink or symbolic link.
Syntax: int symlink(const char *filename1,const char *filename2);
or
int symlink(original_name, alias_name)
Filename1=original_name
Filename2=alias_name

If the original file is deleted,the alias file will becomes useless,that is,it
will lose its content too.

Eg:

o/p:

#include <stdio.h>
main()
{
symlink(oldfile", newfile);
}
$cat oldfile
hello world
$cat newfile
helloworld

unlink()
The opposite of the link() system call is the unlink() system call.
Syntax: int unlink(const char *filename1);
unlink() fails if any of the following conditions holds:
A path name component does not exist.

file_name does not exist.

file_name is a directory and you are not the superuser.

the directory for the file named by file_name is not writable.

the directory is contained in a file system mounted read-only.


Eg:
#include <stdio.h>
main()
{
unlink(file");
}
The link count of the file referred to the path1 will be incremented by 1,
If unlink,the path1 will be decremented by 1

Chmod()
To change the file and directory permissions for three types of system
users-user,group,others.
Syntax: int chmod(const char * filename,int mode);
filename : name of file,absolute or relative path
mode : file access permissions
Eg:

o/p:

#include<stdio.h>
main()
{
chmod(dir1,0777);
}
$ls l dir1
-rwxrwxrwx.

Chown()
To change the owner or group of given files
Syntax: int chown (const char *filename,uid_t UID,gid_t GID);
filename : name of file,absolute or relative path
UID : represents the ID of the owner ie., user
Gid : represents the ID of the group
Eg:

#include<stdio.h>

main()
{
chown(m.txt,102,12);
}
o/p:
$ls l dir1
-rwxrwxrwx 1
102
12
File permissions

links

owner

group

46
bytes

jan 22 08:45 m.txt


Date ,time

filename

Mkdir():Make or Create directory


Returns 0 on success
Returns 1 on failure
Syntax: int mkdir(const char *filename,mode_t);
Eg:

o/p:

#include<stdio.h>
main()
{
mkdir(dirname,0777);
}
./a.out
$ls
dirname

rmdir(): Remove directory

Returns 0 on success
Returns 1 on failure
Syntax: int mkdir(const char *filename,mode_t);

Eg:

o/p:

#include<stdio.h>
main()
{
rmdir(dirname);
}
./a.out
$ls

chdir(): change directory


Syntax: int chdir(const char *pathname);

Eg:

o/p:

#include<stdio.h>
main()
{
chdir(/home/usract/dirname);
}
$./a.out
/home/usract/dirname

Getcwd():It displays the current working Directory


Syntax: char *getcwd( char * buf,size_t size);
getcwd() writes the name of the current directory into the specified
buffer buf.it returns NULL if directory name exceeds the size of the
buffer defined through parameter size.
When succesful it returns buffer buf containing the name of the
directory.
Eg:
#include <stdio.h>
main()
{
char buf[1024];
getcwd(buf,1024);
printf(" The current working directory is %s\n,buf);
}
o/p:
$./a.out
/home/usrsct/abcd

DIRECTORY HANDLING SYSTEM CALLS


1.
2.
3.
4.
5.
6.

Opendir()
Closedir()
Readdir()
Telldir()
Seekdir()
Rewinddir()

opendir()
The opendir function opens a directory and establishes a directory stream.
#include<dirent.h>
Syntax:DIR *opendir(const char *path);/* directory path name*/
DIR data structure is defined in the <direct.h> or <sys/dir.h>
It returns the DIR pointer or NULL on error

Eg: DIR *mydir;


mydir=opendir(home/usract/dir);

closedir()
The closedir() close the directory.

#include<dirent.h>
Syntax: int closedir(DIR *dirp)

/* DIR pointer from opendir*/

It returns a zero (0) on success or -1 on error

readdir()
It reads the next directory record from a directory file referenced by the
dirp(directory pointer) argument.
#include<dirent.h>
Syntax:Struct dirent *readdir(DIR *dirp); * DIR pointer from opendir*
Returns structure or NULL on EOF or error
struct dirent
{
u-long d_ino;
/* i-node number for the dir entry */
u_short d_reclen;
/* length of this record */
u_short d_namelen ;
/* length of the string in d_name */
char d_name[MAXNAMLEN+1] ;
/* directory name */
};

telldir()
It returns the current location in directory stream.
#include<direct.h>
Syntax: Off_t telldir(DIR *dirp); /* DIR pointer from opendir*/
returns the current location in the directory stream or -1 if an error
occurs;

seekdir()
Set the position of the next readdir() call in the directory stream.
Seekdir function sets the directory entry pointer in the directory
stream given by dirp.
The value of loc used to set the position.
Seekdir() should be used with an offset returned by telldir().
#include<sys/types.h>
#include<direct.h>
Syntax:Void seekdir(DIR *dirp, long int loc);

rewinddir()
This function resets a file pointer associated with a dir_fdesc, so that if
readdir is called again ,it will scan the directory from the beginning.
#include<direct.h>
Syntax: void rewinddir(DIR* dir_fdesc)

/*opendir(),readdir(),telldir(),seekdir(),rewinddir(),closedir()*/
#include<stdio.h>
#include<dirent.h>
main()
{
dir *mydir;
struct dirent *files;
mydir=opendir(/home/usract/syscall);
while(files=readdir(mydir))
printf(\n the current position is %ld\n,telldir(mydir));
seekdir(mydir,1024);
printf(\n the current position is %ld\n,telldir(mydir));
rewinddir(mydir);
printf(\n the current position is %ld\n,telldir(mydir));
closedir(mydir);
}
o/p:
List the files in /home/usract/syscall
the current position is 24454545454
the current position is 1024

the current position is 0

You might also like