SlideShare a Scribd company logo
Introduction to System calls
• Objectives
• Understanding system calls
• System calls and library functions
• Interfacing functions between user space and kernel space
• Types of system calls
• File management
• Process management
• Device management
• Information and maintenance
• Process communication
• Programs implementing system calls
Operating system services
• An Operating system provides an environment for the execution of
programs.
• It provides set of services to programs and to users of those programs.
• One set of services provides functions that are helpful to the user
– User interface
– Program execution
– I/O operations
– File system manipulations
– Communications
– Error detection
• Another set of services exists not for helping the user but rather for
ensuring the efficient operation of the system itself.
– Resource allocation
– Accounting
– Protection and security
User related services
• User interface
– Almost all OS have a user interface (UI)
– These can Command line interface (CLI), Batch (in which commands are entered in files)
and Graphical user interface (GUI)
• Program execution
– The system must be able to load the program in memory and execute.
• I/O operation
– A running program may require I/O, which may involve a file and an I/O device.
– For efficiency and protection purpose , users cannot control I/O devices directly.
– OS must provides means to do I/O
• File system manipulations
– Programs needs to read and write files and directories
– Also create, delete, search and list files
– Permission management to allow or deny access to files and directories
• Communication
– Communication between process executing on same computer or
between processes that are executing on different computer systems
tied together by computer networks
– Communication can be implemented via “shared memory” or through
“message passing” in which case packets of information moves
between processes by the OS.
• Error detection
– OS needs to be constantly aware of possible errors. Errors may occur
• In CPU or memory hardware (such as memory error or power
failure),
• In I/O devices (lack of paper in printer or connection failure on
network)
• In User programs (arithmetic over flow or an attempt to access an
illegal memory location)
System related services
• Resource allocation
– When there are multiple users running at the same time, resources
must be allocated to each of them.
– Many different types of resources are managed by the OS such as
• Main memory
• File storage
• CPU cycles
• Accounting
– Keeping track of users activity and resource allocation and utilization
– Usage statistics may be valuable tool for researchers who wish to
reconfigure the system to improve computing services
System related services
• Protection and security
– When several processes execute concurrently, it not be possible for
one process to interfere with the others or with the operating system
itself.
– Protection involves ensuring that all access to system resources is
controlled
– Security of the system from the outsiders is also important
– Such security starts with requiring each user to authenticate himself
or herself to the system, usually by means of password to gain access
to the system resources.
User operating system interface
• Two approaches for users to interface with the operating system
– Command line interface (CLI) or command interpreter
– Graphical user interface (GUI)
• Command line interface or command interpreters
– Command interpreters on Linux are special programs that the program is initiated or
when the user first logs in.
– On systems with multiple command interpreters to choose from, the interpreters are
known as ‘shells’
– On Linux systems, there are several different shells a user may choose from, including
Bourne shell, C shell, Korn shell
– Most shell provides similar functionality with minor differences
– The main function of the command interpreter is to get and execute the next user-
specific command.
Graphical user interface
• GUI provides a mouse based, window-and-menu system as an interface
• A GUI provides a desktop metaphor where the mouse is moved to
position its pointer moves.
• Depending on the mouse pointer’s location, clicking a button on the
mouse can invoke a program, select a file or directory
• X-Windows systems is GUI example on Linux systems
• On Linux systems there are various open source projects
– K desktop environment (KDE)
– GNOME desktop
System calls
• All operating systems provides some mechanism to request services from
the kernel.
• This service request points are called “system calls”
• In Linux system, there is an interface layer between the user space and
kernel space. This layer consists of library made up of functions that
communicate between normal user applications and the Kernel.
• This implementation of C library is called libc/glibc. This provides wrapper
functions for the system calls.
• System calls are implemented using software interrupt or trap.
• System call transfer control to the operating system. It sets the system call
number, the C arguments into the general registers and then executes
some machine instruction that generates a software interrupt in the
kernel.
Example on how system calls are used
• Writing a simple program to read
data from one file and copy them
to another file
• Program inputs
– Name of two files
• Program opens the input file and
create output file and open it
• Each of these operations require
another system calls
• Now that both files are setup,
enter into the loop that read
from input file (system call) and
writes into the output file
(another system call)
Interfacing between user and kernel
space
Library functions
• Library functions are the general purpose functions defined in Section 3 of
“Linux/Unix programmers Manual”
• $ man <section_no> <command_name>
• These functions are not entry points into the kernel although they may
invoke one or more of the kernel functions.
• For example, ‘printf’ may invoke the ‘write’ system call to perform the
output .
• ‘strcpy’ and ‘atoi’ doesn’t invoke the kernel service at all. They are library
functions
C library interface
• The standard C library provides a
portion of the system call
interface for many versions of
UNIX and Linux
• For example, the ‘printf’
statement. The C library
interprets this call and invokes
the necessary system call(s) in
the operating system in this
instance , the write() system call
• The C library takes the value
returned by write() and passes it
back to the user program.
User Space
system call and library function
• Examples of systems
calls
• Read() / write ()
• Fork()/ exec ()
• Example of library
functions
• Date/time
• Strcpy/atoi/printf
Application code
C library functions
System calls
Header Files
• The Application
programming interface (API)
of the C standard library is
declared in a number of
header files. Each header
files contains one or more
function declarations, data
types definitions and
macros.
• Header files are located
at /usr/include
Name Description
<errno.h>
Testing error code reported by library
functions.
<stdarg.h>
For accessing varying number of
arguments passed to functions
<stdatomic.h>
For atomic operations on data shared
between threads
<stddef.h> Defines several types and macros
<stdio.h> Defines core input/output APIS
<stdlib.h>
Defines memory allocation/process
control
<string.h> Defines string manipulations APIs.
<threads.h> Thread handling APIs
<time.h> Date/Time handling APIs
System call categories
• System calls can be roughly
grouped into five major
categories:
– Process management
– File management
– Device management
– Information/Maintenance
– Communication
• Process management
– create process the process
– Terminate process
– Load the process
– Execute the process
– get/set process attributes
– wait for time, wait event,
signal event
System call categories..contd…
• File management.
– create file, delete file
– open, close
– read, write, reposition
– get/set file attributes
• Device Management.
– request device, release
device
– read, write, reposition
– get/set device attributes
– logically attach or detach
devices
• Information Maintenance.
– get/set time or date
– get/set system data
– get/set process, file, or device
attributes
• Communication.
– create, delete communication
connection
– send, receive messages
– transfer status information
– attach or detach remote
devices
File management
• We will start our study with the functions available for the file I/O
operations such as open a file, read & write a file, close a file and so on.
• Most file IO operations are performed with the open, read, write, lseek
and close system calls.
• File descriptors
– File descriptor is a non-negative integer representing the file opened
in the kernel.
– When file is opened or newly created, the kernel returns a file
descriptor to the process.
– During read/write, the file is identified by the file descriptor that was
returned by open()
Open function
Open and possibly create a file or device
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
int creat(const char *pathname, mode_t mode);
DESCRIPTION
Given a pathname for a file, open() returns a file descriptor, a small, nonnegative
integer for use in subsequent system calls (read, write, lseek, fcntl, etc.).
Flags : One of the access modes: O_RDONLY, O_WRONLY, or O_RDWR. These
request opening the file read-only, write-only, or read/write, respectively.
RETURN VALUE
open() and creat() return the new file descriptor, or -1 if an error occurred (in
which case, errno is set appropriately).
Handling open system call
Close function
Close a file descriptor
SYNOPSIS
#include <unistd.h>
int close(int fd);
DESCRIPTION
close() closes a file descriptor, so that it no longer refers to any file and
may be reused.
RETURN VALUE
close() returns zero on success. On error, -1 is returned, and errno is set
appropriately.
Read function
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 count bytes from file descriptor fd into the
buffer starting at buf.
If count is zero, read() returns zero and has no other results. 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. On error, -1 is
returned, and errno is set appropriately.
Write function
Write to a file descriptor
SYNOPSIS
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
DESCRIPTION
write() writes up to count bytes from the buffer pointed buf to the file
referred to by the file descriptor fd.
RETURN VALUE
On success, the number of bytes written is returned (zero indicates
nothing was written). On error, -1 is returned, and errno is set
appropriately.
Open, close, read and write calls
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main (){
int fd, read_bytes;
char buff[256];
fd = open("./test_file_op",
O_RDWR);
if (fd < 0)
printf("Error opening filen");
printf("FD (%d)n", fd);
read_bytes = read(fd, buff, 15);
if (read_bytes < 0)
printf("Read Errorn");
printf("File contentsn");
printf("%sn", buff);
strcpy(buff,
"testing_write_system_call");
read_bytes = write(fd, buff, 20);
close(fd);
}
lseek function
lseek - reposition read/write file offset
SYNOPSIS
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
DESCRIPTION
The lseek() function repositions the offset of the open file associated with the file
descriptor fd to the argument offset according to the directive whence as follows:
SEEK_SET - The offset is set to offset bytes.
SEEK_CUR - The offset is set to its current location plus offset bytes.
SEEK_END – The offset is set to the size of the file plus offset bytes
RETURN VALUE
Upon successful completion, lseek() returns the resulting offset location as
measured in bytes from the beginning of the file. Otherwise, a value of (off_t) -1
is returned and errno is set to indicate the error.
access
• Testing file permissions
SYNOPSIS
– Access (const char *pathname, permission_flags)
– Permission flags - R_OK, W_OK, X_OK for read, write and execute permissions.
DESCRIPTION
The access system call determines whether the calling process has access
permission to a file.
– It can check any combination of read (r), write (w) and execute (x) permission.
– It can also check whether file exists or not.
RETURN VALUE
On success return value is 0, if process has all specified permissions,
If the file exists and process does not have the specified permissions, access
returns -1 and errno is set to EACCESS.
System call File Operation
open open a file or device fs/open.c
creat create a file or device
close close a file descriptor
dup2 duplicate a file descriptor
dup duplicate an open file descriptor
mmap map files into memory
(Only the PROT_READ protection flag is supported.)
munmap unmap files from memory
pread read from a file descriptor at a given offset
pwrite write to a file descriptor at a given offset
read read from a file descriptor
readv read data from multiple buffers
write write to a file descriptor
writev write data from multiple buffers
lseek reposition read/write file offset
llseek move extended read/write file pointer
lstat get file status
truncate set a file to a specified length
ftruncate set a file to a specified length
unlink delete a name and possibly the file it refers to
System call Sync Operation
sync update the super block
fsync synchronize the complete in-
core state of a file with that on
disk
System call
Statistics and status
Operation
fstatfs get file system statistics
fstat get file status
statfs get file system statistics
stat get file status
System call Directory Operation
chdir change working directory
chroot change root directory
fchdir change working directory
rmdir remove a directory
rename change the name or location of
a file
getdents read directory entries
mkdir create a directory
System call Permission Operation
chmod change permissions of a file
chown change ownership of a file
fchmod change access permission
mode of file
fchown change owner and group of a
file
Getrlimit and setrlimit: resource limit
• The getrlimit and setrlimit system calls allow a process to read and set
limits on the system resources that it can consume.
• For each resource, there are two limits
– Hard limit
– Soft limit
• Both getrlimit and setrlimit take as arguments a code specifying the
resource limit type and a pointer to a structrlimit variable.
• The getrlimit call fills the fields of this structure, while the setrlimit call
changes the limit based on its contents.
• The rlimit structure has two fields: rlim_cur is the soft limit, and rlim_max
is the hard limit.
• Most useful resource limits that may be changed are listed here, with their codes:
• RLIMIT_CPU
– The maximum CPU time, in seconds, used by a program. This is the amount of
time that the program is actually executing on the CPU, which is not
necessarily the same as wall-clock time.
– If the program exceeds this time limit, it is terminated with a SIGXCPU signal.
• RLIMIT_DATA
– The maximum amount of memory that a program can allocate for its data.
Additional allocation beyond this limit will fail.
• RLIMIT_NPROC
– The maximum number of child processes that can be running for this user. If
the process calls fork and too many processes belonging to this user are
running on the system, fork fails.
• RLIMIT_NOFILE
– The maximum number of file descriptors that the process may have open at
one time.
CPU-Time limit demonstration
• The program illustrates setting
the limit on CPU time consumed
by a program.
• It sets a 1-second CPU time limit
and then spins in an infinite loop.
Linux kills the process soon
afterward, when it exceeds 1
second of CPU time.
• When the program is terminated
by SIGXCPU, the shell helpfully
prints out a message interpreting
the signal:
• $ ./limit_cpu
• CPU time limit exceeded
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
int main () {
struct rlimit rl;
/* Obtain the current limits. */
getrlimit (RLIMIT_CPU, &rl);
/* Set a CPU limit of 1 second. */
rl.rlim_cur = 1;
setrlimit (RLIMIT_CPU, &rl);
/* Do busy work. */
while (1);
return 0;
}
Getrusage- Process statistics
• The getrusage system call retrieves process statistics from the kernel.
• Syntax : man getrusage
• It can be used to obtain statistics either for the current process by passing
RUSAGE_SELF as the first argument, or for all terminated child processes that were
forked by this process and its children by passing RUSAGE_CHILDREN.
• The second argument to rusage is a pointer to a struct rusage variable, which is
filled with the statistics.
• A few of the more interesting fields in struct rusage are listed here:
– ru_utime—A struct timeval field containing the amount of user time, in
seconds, that the process has used. User time is CPU time spent executing the
user program, rather than in kernel system calls.
– ru_stime—A struct timeval field containing the amount of system time, in
seconds, that the process has used. System time is the CPU time spent
executing system calls on behalf of the process.
– ru_maxrss—The largest amount of physical memory occupied by the
process’s data at one time over the course of its execution.
Display Process user and system time
• A few of the more interesting fields in
struct rusage are listed here:
• ru_utime—A struct timeval field
containing the amount of user time, in
seconds, that the process has used. User
time is CPU time spent executing the
user program, rather than in kernel
system calls.
• ru_stime—A struct timeval field
containing the amount of system time,
in seconds, that the process has used.
System time is the CPU time spent
executing system calls on behalf of the
process.
• ru_maxrss—The largest amount of
physical memory occupied by the
process’s data at one time over the
course of its execution.
#include <stdio.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
void main () {
struct rusage usage;
getrusage (RUSAGE_SELF,
&usage);
printf (“CPU time: %ld.%06ld sec
user, %ld.%06ld sec systemn”,
usage.ru_utime.tv_sec,
usage.ru_utime.tv_usec,
usage.ru_stime.tv_sec,
usage.ru_stime.tv_usec);
return 0;
}
Sysinfo: Obtaining system statistics
• The sysinfo system call fills a structure with system statistics. Its only
argument is a pointer to a struct sysinfo.
• Syntax : man sysinfo
• Some of the more interesting fields of struct sysinfo that are filled include
these:
• uptime—Time elapsed since the system booted, in seconds
• totalram—Total available physical RAM
• freeram—Free physical RAM
• procs—Number of processes on the system
Print system statistics
#include <linux/kernel.h>
#include <linux/sys.h>
#include <stdio.h>
#include <sys/sysinfo.h>
int main () {
/* Conversion constants. */
const long minute = 60;
const long hour = minute * 60;
const long day = hour * 24;
const double megabyte = 1024 * 1024;
/* Obtain system statistics. */
struct sysinfo si;
sysinfo (&si);
/* Summarize interesting values. */
printf (“system uptime : %ld days, %ld:
%02ld:%02ldn”,
si.uptime / day, (si.uptime % day) /
hour, (si.uptime % hour) / minute,
si.uptime % minute);
printf (“total RAM : %5.1f MBn”,
si.totalram / megabyte);
printf (“free RAM : %5.1f MBn”,
si.freeram / megabyte);
printf (“process count : %dn”, si.procs);
Return 0
}
Uname system
• The uname system call fills a structure with various system information,
including the computer’s network name and domain name, and the
operating system version it’s running.
• Syntax : man uname
• A single argument, a pointer to a struct utsname object.
• The call to uname fills in these fields:
– sysname—The name of the operating system (such as Linux).
– release, version—The Linux kernel release number and version level.
– machine—Some information about the hardware platform running
Linux. For x86 Linux, this is i386 or i686, depending on the processor.
– node—The computer’s unqualified hostname.
– __domain—The computer’s domain name.
• Each of these fields is a character string.
Print linux verion number and
hardware information
#include <stdio.h>
#include <sys/utsname.h>
int main ()
{
struct utsname u;
uname (&u);
printf (“%s release %s (version %s) on %sn”, u.sysname, u.release,
u.version, u.machine);
return 0;
}
Few refences
• Linux system call quick reference :
– http://www.digilife.be/quickreferences/qrc/linux%20system%20call%20quic
• Linux system call table:
– http://docs.cs.up.ac.za/programming/asm/derick_tut/syscalls.html
• Operating system concepts(Galvin), chapter 2

More Related Content

What's hot

Operating system services 9
Operating system services 9Operating system services 9
Operating system services 9myrajendra
 
OS - Process Concepts
OS - Process ConceptsOS - Process Concepts
OS - Process Concepts
Mukesh Chinta
 
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURESOPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
priyasoundar
 
Context switching
Context switchingContext switching
Context switching
DarakhshanNayyab
 
Process and Threads in Linux - PPT
Process and Threads in Linux - PPTProcess and Threads in Linux - PPT
Process and Threads in Linux - PPT
QUONTRASOLUTIONS
 
Process management os concept
Process management os conceptProcess management os concept
Process management os concept
priyadeosarkar91
 
Operating system 02 os as an extended machine
Operating system 02 os as an extended machineOperating system 02 os as an extended machine
Operating system 02 os as an extended machine
Vaibhav Khanna
 
Process management in linux
Process management in linuxProcess management in linux
Process management in linux
Mazenetsolution
 
Processes in unix
Processes in unixProcesses in unix
Processes in unixmiau_max
 
Os Threads
Os ThreadsOs Threads
Os Threads
Salman Memon
 
Operating Systems - "Chapter 4: Multithreaded Programming"
Operating Systems - "Chapter 4:  Multithreaded Programming"Operating Systems - "Chapter 4:  Multithreaded Programming"
Operating Systems - "Chapter 4: Multithreaded Programming"
Ra'Fat Al-Msie'deen
 
Operating Systems Process Scheduling Algorithms
Operating Systems   Process Scheduling AlgorithmsOperating Systems   Process Scheduling Algorithms
Operating Systems Process Scheduling Algorithms
sathish sak
 
Operating system architecture
Operating system architectureOperating system architecture
Operating system architecture
Sabin dumre
 
Ch1-Operating System Concept
Ch1-Operating System ConceptCh1-Operating System Concept
Ch1-Operating System Concept
Muhammad Bilal Tariq
 
Shell programming
Shell programmingShell programming
Shell programming
Moayad Moawiah
 
Advanced Operating System- Introduction
Advanced Operating System- IntroductionAdvanced Operating System- Introduction
Advanced Operating System- Introduction
Debasis Das
 
Lesson 2 Understanding Linux File System
Lesson 2 Understanding Linux File SystemLesson 2 Understanding Linux File System
Lesson 2 Understanding Linux File System
Sadia Bashir
 
Multithreading
MultithreadingMultithreading
Multithreading
A B Shinde
 
Introduction to Unix
Introduction to UnixIntroduction to Unix
Introduction to Unix
Nishant Munjal
 

What's hot (20)

operating system structure
operating system structureoperating system structure
operating system structure
 
Operating system services 9
Operating system services 9Operating system services 9
Operating system services 9
 
OS - Process Concepts
OS - Process ConceptsOS - Process Concepts
OS - Process Concepts
 
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURESOPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
 
Context switching
Context switchingContext switching
Context switching
 
Process and Threads in Linux - PPT
Process and Threads in Linux - PPTProcess and Threads in Linux - PPT
Process and Threads in Linux - PPT
 
Process management os concept
Process management os conceptProcess management os concept
Process management os concept
 
Operating system 02 os as an extended machine
Operating system 02 os as an extended machineOperating system 02 os as an extended machine
Operating system 02 os as an extended machine
 
Process management in linux
Process management in linuxProcess management in linux
Process management in linux
 
Processes in unix
Processes in unixProcesses in unix
Processes in unix
 
Os Threads
Os ThreadsOs Threads
Os Threads
 
Operating Systems - "Chapter 4: Multithreaded Programming"
Operating Systems - "Chapter 4:  Multithreaded Programming"Operating Systems - "Chapter 4:  Multithreaded Programming"
Operating Systems - "Chapter 4: Multithreaded Programming"
 
Operating Systems Process Scheduling Algorithms
Operating Systems   Process Scheduling AlgorithmsOperating Systems   Process Scheduling Algorithms
Operating Systems Process Scheduling Algorithms
 
Operating system architecture
Operating system architectureOperating system architecture
Operating system architecture
 
Ch1-Operating System Concept
Ch1-Operating System ConceptCh1-Operating System Concept
Ch1-Operating System Concept
 
Shell programming
Shell programmingShell programming
Shell programming
 
Advanced Operating System- Introduction
Advanced Operating System- IntroductionAdvanced Operating System- Introduction
Advanced Operating System- Introduction
 
Lesson 2 Understanding Linux File System
Lesson 2 Understanding Linux File SystemLesson 2 Understanding Linux File System
Lesson 2 Understanding Linux File System
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Introduction to Unix
Introduction to UnixIntroduction to Unix
Introduction to Unix
 

Similar to Introduction to System Calls

operating system calls input and output by (rohit malav)
operating system calls input and output by (rohit malav)operating system calls input and output by (rohit malav)
operating system calls input and output by (rohit malav)
Rohit malav
 
Services and system calls
Services and system callsServices and system calls
Services and system calls
sangrampatil81
 
chapter2.pptx
chapter2.pptxchapter2.pptx
chapter2.pptx
PardhisCreation
 
Ch2 operating-system structures
Ch2   operating-system structuresCh2   operating-system structures
Ch2 operating-system structures
Welly Dian Astika
 
Operating System Structure Part-I.pdf
Operating System Structure Part-I.pdfOperating System Structure Part-I.pdf
Operating System Structure Part-I.pdf
Harika Pudugosula
 
OS Services, System call, Virtual Machine
OS Services, System call, Virtual MachineOS Services, System call, Virtual Machine
OS Services, System call, Virtual Machine
Divya S
 
operatinndnd jdj jjrg-system-1(1) (1).pptx
operatinndnd jdj jjrg-system-1(1) (1).pptxoperatinndnd jdj jjrg-system-1(1) (1).pptx
operatinndnd jdj jjrg-system-1(1) (1).pptx
krishnajoshi70
 
Os unit 1(cont)
Os unit 1(cont)Os unit 1(cont)
OS - Ch2
OS - Ch2OS - Ch2
OS - Ch2sphs
 
Chapter 2 - Operating System Structures
Chapter 2 - Operating System StructuresChapter 2 - Operating System Structures
Chapter 2 - Operating System StructuresWayne Jones Jnr
 
Operating System 2
Operating System 2Operating System 2
Operating System 2
tech2click
 
2 operating system structures
2 operating system structures2 operating system structures
2 operating system structures
Dr. Loganathan R
 
Lecture_02_Operating System Structures Operating Systems
Lecture_02_Operating System Structures Operating SystemsLecture_02_Operating System Structures Operating Systems
Lecture_02_Operating System Structures Operating Systems
ArnoyKhan
 
OS UNIT 1 PPT.pptx
OS UNIT 1 PPT.pptxOS UNIT 1 PPT.pptx
OS UNIT 1 PPT.pptx
PRABAVATHIH
 
Unit 4
Unit  4Unit  4
Unit 4
pm_ghate
 
Operating-System Structures
Operating-System StructuresOperating-System Structures
Operating-System Structures
Cloudbells.com
 
OS Content.pdf
OS Content.pdfOS Content.pdf
OS Content.pdf
VAIBHAVSAHU55
 
Chapter 1 Introduction to Operating System Concepts
Chapter 1 Introduction to Operating System ConceptsChapter 1 Introduction to Operating System Concepts
Chapter 1 Introduction to Operating System Concepts
MeenalJabde
 

Similar to Introduction to System Calls (20)

operating system calls input and output by (rohit malav)
operating system calls input and output by (rohit malav)operating system calls input and output by (rohit malav)
operating system calls input and output by (rohit malav)
 
Services and system calls
Services and system callsServices and system calls
Services and system calls
 
chapter2.pptx
chapter2.pptxchapter2.pptx
chapter2.pptx
 
Ch2 operating-system structures
Ch2   operating-system structuresCh2   operating-system structures
Ch2 operating-system structures
 
Operating System Structure Part-I.pdf
Operating System Structure Part-I.pdfOperating System Structure Part-I.pdf
Operating System Structure Part-I.pdf
 
OS Services, System call, Virtual Machine
OS Services, System call, Virtual MachineOS Services, System call, Virtual Machine
OS Services, System call, Virtual Machine
 
operatinndnd jdj jjrg-system-1(1) (1).pptx
operatinndnd jdj jjrg-system-1(1) (1).pptxoperatinndnd jdj jjrg-system-1(1) (1).pptx
operatinndnd jdj jjrg-system-1(1) (1).pptx
 
Os unit 1(cont)
Os unit 1(cont)Os unit 1(cont)
Os unit 1(cont)
 
Ch2
Ch2Ch2
Ch2
 
OS - Ch2
OS - Ch2OS - Ch2
OS - Ch2
 
Chapter 2 - Operating System Structures
Chapter 2 - Operating System StructuresChapter 2 - Operating System Structures
Chapter 2 - Operating System Structures
 
Operating System 2
Operating System 2Operating System 2
Operating System 2
 
2 operating system structures
2 operating system structures2 operating system structures
2 operating system structures
 
Lecture_02_Operating System Structures Operating Systems
Lecture_02_Operating System Structures Operating SystemsLecture_02_Operating System Structures Operating Systems
Lecture_02_Operating System Structures Operating Systems
 
OS UNIT 1 PPT.pptx
OS UNIT 1 PPT.pptxOS UNIT 1 PPT.pptx
OS UNIT 1 PPT.pptx
 
Unit 4
Unit  4Unit  4
Unit 4
 
Operating-System Structures
Operating-System StructuresOperating-System Structures
Operating-System Structures
 
OS Content.pdf
OS Content.pdfOS Content.pdf
OS Content.pdf
 
Chapter 1 Introduction to Operating System Concepts
Chapter 1 Introduction to Operating System ConceptsChapter 1 Introduction to Operating System Concepts
Chapter 1 Introduction to Operating System Concepts
 
App A
App AApp A
App A
 

Recently uploaded

ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
MuhammadTufail242431
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
Kamal Acharya
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
Kamal Acharya
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 

Recently uploaded (20)

ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 

Introduction to System Calls

  • 1. Introduction to System calls • Objectives • Understanding system calls • System calls and library functions • Interfacing functions between user space and kernel space • Types of system calls • File management • Process management • Device management • Information and maintenance • Process communication • Programs implementing system calls
  • 2. Operating system services • An Operating system provides an environment for the execution of programs. • It provides set of services to programs and to users of those programs. • One set of services provides functions that are helpful to the user – User interface – Program execution – I/O operations – File system manipulations – Communications – Error detection • Another set of services exists not for helping the user but rather for ensuring the efficient operation of the system itself. – Resource allocation – Accounting – Protection and security
  • 3. User related services • User interface – Almost all OS have a user interface (UI) – These can Command line interface (CLI), Batch (in which commands are entered in files) and Graphical user interface (GUI) • Program execution – The system must be able to load the program in memory and execute. • I/O operation – A running program may require I/O, which may involve a file and an I/O device. – For efficiency and protection purpose , users cannot control I/O devices directly. – OS must provides means to do I/O • File system manipulations – Programs needs to read and write files and directories – Also create, delete, search and list files – Permission management to allow or deny access to files and directories
  • 4. • Communication – Communication between process executing on same computer or between processes that are executing on different computer systems tied together by computer networks – Communication can be implemented via “shared memory” or through “message passing” in which case packets of information moves between processes by the OS. • Error detection – OS needs to be constantly aware of possible errors. Errors may occur • In CPU or memory hardware (such as memory error or power failure), • In I/O devices (lack of paper in printer or connection failure on network) • In User programs (arithmetic over flow or an attempt to access an illegal memory location)
  • 5. System related services • Resource allocation – When there are multiple users running at the same time, resources must be allocated to each of them. – Many different types of resources are managed by the OS such as • Main memory • File storage • CPU cycles • Accounting – Keeping track of users activity and resource allocation and utilization – Usage statistics may be valuable tool for researchers who wish to reconfigure the system to improve computing services
  • 6. System related services • Protection and security – When several processes execute concurrently, it not be possible for one process to interfere with the others or with the operating system itself. – Protection involves ensuring that all access to system resources is controlled – Security of the system from the outsiders is also important – Such security starts with requiring each user to authenticate himself or herself to the system, usually by means of password to gain access to the system resources.
  • 7. User operating system interface • Two approaches for users to interface with the operating system – Command line interface (CLI) or command interpreter – Graphical user interface (GUI) • Command line interface or command interpreters – Command interpreters on Linux are special programs that the program is initiated or when the user first logs in. – On systems with multiple command interpreters to choose from, the interpreters are known as ‘shells’ – On Linux systems, there are several different shells a user may choose from, including Bourne shell, C shell, Korn shell – Most shell provides similar functionality with minor differences – The main function of the command interpreter is to get and execute the next user- specific command.
  • 8. Graphical user interface • GUI provides a mouse based, window-and-menu system as an interface • A GUI provides a desktop metaphor where the mouse is moved to position its pointer moves. • Depending on the mouse pointer’s location, clicking a button on the mouse can invoke a program, select a file or directory • X-Windows systems is GUI example on Linux systems • On Linux systems there are various open source projects – K desktop environment (KDE) – GNOME desktop
  • 9. System calls • All operating systems provides some mechanism to request services from the kernel. • This service request points are called “system calls” • In Linux system, there is an interface layer between the user space and kernel space. This layer consists of library made up of functions that communicate between normal user applications and the Kernel. • This implementation of C library is called libc/glibc. This provides wrapper functions for the system calls. • System calls are implemented using software interrupt or trap. • System call transfer control to the operating system. It sets the system call number, the C arguments into the general registers and then executes some machine instruction that generates a software interrupt in the kernel.
  • 10. Example on how system calls are used • Writing a simple program to read data from one file and copy them to another file • Program inputs – Name of two files • Program opens the input file and create output file and open it • Each of these operations require another system calls • Now that both files are setup, enter into the loop that read from input file (system call) and writes into the output file (another system call)
  • 11. Interfacing between user and kernel space
  • 12. Library functions • Library functions are the general purpose functions defined in Section 3 of “Linux/Unix programmers Manual” • $ man <section_no> <command_name> • These functions are not entry points into the kernel although they may invoke one or more of the kernel functions. • For example, ‘printf’ may invoke the ‘write’ system call to perform the output . • ‘strcpy’ and ‘atoi’ doesn’t invoke the kernel service at all. They are library functions
  • 13. C library interface • The standard C library provides a portion of the system call interface for many versions of UNIX and Linux • For example, the ‘printf’ statement. The C library interprets this call and invokes the necessary system call(s) in the operating system in this instance , the write() system call • The C library takes the value returned by write() and passes it back to the user program.
  • 14. User Space system call and library function • Examples of systems calls • Read() / write () • Fork()/ exec () • Example of library functions • Date/time • Strcpy/atoi/printf Application code C library functions System calls
  • 15. Header Files • The Application programming interface (API) of the C standard library is declared in a number of header files. Each header files contains one or more function declarations, data types definitions and macros. • Header files are located at /usr/include Name Description <errno.h> Testing error code reported by library functions. <stdarg.h> For accessing varying number of arguments passed to functions <stdatomic.h> For atomic operations on data shared between threads <stddef.h> Defines several types and macros <stdio.h> Defines core input/output APIS <stdlib.h> Defines memory allocation/process control <string.h> Defines string manipulations APIs. <threads.h> Thread handling APIs <time.h> Date/Time handling APIs
  • 16. System call categories • System calls can be roughly grouped into five major categories: – Process management – File management – Device management – Information/Maintenance – Communication • Process management – create process the process – Terminate process – Load the process – Execute the process – get/set process attributes – wait for time, wait event, signal event
  • 17. System call categories..contd… • File management. – create file, delete file – open, close – read, write, reposition – get/set file attributes • Device Management. – request device, release device – read, write, reposition – get/set device attributes – logically attach or detach devices • Information Maintenance. – get/set time or date – get/set system data – get/set process, file, or device attributes • Communication. – create, delete communication connection – send, receive messages – transfer status information – attach or detach remote devices
  • 18. File management • We will start our study with the functions available for the file I/O operations such as open a file, read & write a file, close a file and so on. • Most file IO operations are performed with the open, read, write, lseek and close system calls. • File descriptors – File descriptor is a non-negative integer representing the file opened in the kernel. – When file is opened or newly created, the kernel returns a file descriptor to the process. – During read/write, the file is identified by the file descriptor that was returned by open()
  • 19. Open function Open and possibly create a file or device #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode); int creat(const char *pathname, mode_t mode); DESCRIPTION Given a pathname for a file, open() returns a file descriptor, a small, nonnegative integer for use in subsequent system calls (read, write, lseek, fcntl, etc.). Flags : One of the access modes: O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read-only, write-only, or read/write, respectively. RETURN VALUE open() and creat() return the new file descriptor, or -1 if an error occurred (in which case, errno is set appropriately).
  • 21. Close function Close a file descriptor SYNOPSIS #include <unistd.h> int close(int fd); DESCRIPTION close() closes a file descriptor, so that it no longer refers to any file and may be reused. RETURN VALUE close() returns zero on success. On error, -1 is returned, and errno is set appropriately.
  • 22. Read function 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 count bytes from file descriptor fd into the buffer starting at buf. If count is zero, read() returns zero and has no other results. 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. On error, -1 is returned, and errno is set appropriately.
  • 23. Write function Write to a file descriptor SYNOPSIS #include <unistd.h> ssize_t write(int fd, const void *buf, size_t count); DESCRIPTION write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd. RETURN VALUE On success, the number of bytes written is returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately.
  • 24. Open, close, read and write calls #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <string.h> int main (){ int fd, read_bytes; char buff[256]; fd = open("./test_file_op", O_RDWR); if (fd < 0) printf("Error opening filen"); printf("FD (%d)n", fd); read_bytes = read(fd, buff, 15); if (read_bytes < 0) printf("Read Errorn"); printf("File contentsn"); printf("%sn", buff); strcpy(buff, "testing_write_system_call"); read_bytes = write(fd, buff, 20); close(fd); }
  • 25. lseek function lseek - reposition read/write file offset SYNOPSIS #include <sys/types.h> #include <unistd.h> off_t lseek(int fd, off_t offset, int whence); DESCRIPTION The lseek() function repositions the offset of the open file associated with the file descriptor fd to the argument offset according to the directive whence as follows: SEEK_SET - The offset is set to offset bytes. SEEK_CUR - The offset is set to its current location plus offset bytes. SEEK_END – The offset is set to the size of the file plus offset bytes RETURN VALUE Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file. Otherwise, a value of (off_t) -1 is returned and errno is set to indicate the error.
  • 26. access • Testing file permissions SYNOPSIS – Access (const char *pathname, permission_flags) – Permission flags - R_OK, W_OK, X_OK for read, write and execute permissions. DESCRIPTION The access system call determines whether the calling process has access permission to a file. – It can check any combination of read (r), write (w) and execute (x) permission. – It can also check whether file exists or not. RETURN VALUE On success return value is 0, if process has all specified permissions, If the file exists and process does not have the specified permissions, access returns -1 and errno is set to EACCESS.
  • 27. System call File Operation open open a file or device fs/open.c creat create a file or device close close a file descriptor dup2 duplicate a file descriptor dup duplicate an open file descriptor mmap map files into memory (Only the PROT_READ protection flag is supported.) munmap unmap files from memory pread read from a file descriptor at a given offset pwrite write to a file descriptor at a given offset read read from a file descriptor readv read data from multiple buffers write write to a file descriptor writev write data from multiple buffers lseek reposition read/write file offset llseek move extended read/write file pointer lstat get file status truncate set a file to a specified length ftruncate set a file to a specified length unlink delete a name and possibly the file it refers to
  • 28. System call Sync Operation sync update the super block fsync synchronize the complete in- core state of a file with that on disk System call Statistics and status Operation fstatfs get file system statistics fstat get file status statfs get file system statistics stat get file status System call Directory Operation chdir change working directory chroot change root directory fchdir change working directory rmdir remove a directory rename change the name or location of a file getdents read directory entries mkdir create a directory System call Permission Operation chmod change permissions of a file chown change ownership of a file fchmod change access permission mode of file fchown change owner and group of a file
  • 29. Getrlimit and setrlimit: resource limit • The getrlimit and setrlimit system calls allow a process to read and set limits on the system resources that it can consume. • For each resource, there are two limits – Hard limit – Soft limit • Both getrlimit and setrlimit take as arguments a code specifying the resource limit type and a pointer to a structrlimit variable. • The getrlimit call fills the fields of this structure, while the setrlimit call changes the limit based on its contents. • The rlimit structure has two fields: rlim_cur is the soft limit, and rlim_max is the hard limit.
  • 30. • Most useful resource limits that may be changed are listed here, with their codes: • RLIMIT_CPU – The maximum CPU time, in seconds, used by a program. This is the amount of time that the program is actually executing on the CPU, which is not necessarily the same as wall-clock time. – If the program exceeds this time limit, it is terminated with a SIGXCPU signal. • RLIMIT_DATA – The maximum amount of memory that a program can allocate for its data. Additional allocation beyond this limit will fail. • RLIMIT_NPROC – The maximum number of child processes that can be running for this user. If the process calls fork and too many processes belonging to this user are running on the system, fork fails. • RLIMIT_NOFILE – The maximum number of file descriptors that the process may have open at one time.
  • 31. CPU-Time limit demonstration • The program illustrates setting the limit on CPU time consumed by a program. • It sets a 1-second CPU time limit and then spins in an infinite loop. Linux kills the process soon afterward, when it exceeds 1 second of CPU time. • When the program is terminated by SIGXCPU, the shell helpfully prints out a message interpreting the signal: • $ ./limit_cpu • CPU time limit exceeded #include <sys/resource.h> #include <sys/time.h> #include <unistd.h> int main () { struct rlimit rl; /* Obtain the current limits. */ getrlimit (RLIMIT_CPU, &rl); /* Set a CPU limit of 1 second. */ rl.rlim_cur = 1; setrlimit (RLIMIT_CPU, &rl); /* Do busy work. */ while (1); return 0; }
  • 32. Getrusage- Process statistics • The getrusage system call retrieves process statistics from the kernel. • Syntax : man getrusage • It can be used to obtain statistics either for the current process by passing RUSAGE_SELF as the first argument, or for all terminated child processes that were forked by this process and its children by passing RUSAGE_CHILDREN. • The second argument to rusage is a pointer to a struct rusage variable, which is filled with the statistics. • A few of the more interesting fields in struct rusage are listed here: – ru_utime—A struct timeval field containing the amount of user time, in seconds, that the process has used. User time is CPU time spent executing the user program, rather than in kernel system calls. – ru_stime—A struct timeval field containing the amount of system time, in seconds, that the process has used. System time is the CPU time spent executing system calls on behalf of the process. – ru_maxrss—The largest amount of physical memory occupied by the process’s data at one time over the course of its execution.
  • 33. Display Process user and system time • A few of the more interesting fields in struct rusage are listed here: • ru_utime—A struct timeval field containing the amount of user time, in seconds, that the process has used. User time is CPU time spent executing the user program, rather than in kernel system calls. • ru_stime—A struct timeval field containing the amount of system time, in seconds, that the process has used. System time is the CPU time spent executing system calls on behalf of the process. • ru_maxrss—The largest amount of physical memory occupied by the process’s data at one time over the course of its execution. #include <stdio.h> #include <sys/resource.h> #include <sys/time.h> #include <unistd.h> void main () { struct rusage usage; getrusage (RUSAGE_SELF, &usage); printf (“CPU time: %ld.%06ld sec user, %ld.%06ld sec systemn”, usage.ru_utime.tv_sec, usage.ru_utime.tv_usec, usage.ru_stime.tv_sec, usage.ru_stime.tv_usec); return 0; }
  • 34. Sysinfo: Obtaining system statistics • The sysinfo system call fills a structure with system statistics. Its only argument is a pointer to a struct sysinfo. • Syntax : man sysinfo • Some of the more interesting fields of struct sysinfo that are filled include these: • uptime—Time elapsed since the system booted, in seconds • totalram—Total available physical RAM • freeram—Free physical RAM • procs—Number of processes on the system
  • 35. Print system statistics #include <linux/kernel.h> #include <linux/sys.h> #include <stdio.h> #include <sys/sysinfo.h> int main () { /* Conversion constants. */ const long minute = 60; const long hour = minute * 60; const long day = hour * 24; const double megabyte = 1024 * 1024; /* Obtain system statistics. */ struct sysinfo si; sysinfo (&si); /* Summarize interesting values. */ printf (“system uptime : %ld days, %ld: %02ld:%02ldn”, si.uptime / day, (si.uptime % day) / hour, (si.uptime % hour) / minute, si.uptime % minute); printf (“total RAM : %5.1f MBn”, si.totalram / megabyte); printf (“free RAM : %5.1f MBn”, si.freeram / megabyte); printf (“process count : %dn”, si.procs); Return 0 }
  • 36. Uname system • The uname system call fills a structure with various system information, including the computer’s network name and domain name, and the operating system version it’s running. • Syntax : man uname • A single argument, a pointer to a struct utsname object. • The call to uname fills in these fields: – sysname—The name of the operating system (such as Linux). – release, version—The Linux kernel release number and version level. – machine—Some information about the hardware platform running Linux. For x86 Linux, this is i386 or i686, depending on the processor. – node—The computer’s unqualified hostname. – __domain—The computer’s domain name. • Each of these fields is a character string.
  • 37. Print linux verion number and hardware information #include <stdio.h> #include <sys/utsname.h> int main () { struct utsname u; uname (&u); printf (“%s release %s (version %s) on %sn”, u.sysname, u.release, u.version, u.machine); return 0; }
  • 38. Few refences • Linux system call quick reference : – http://www.digilife.be/quickreferences/qrc/linux%20system%20call%20quic • Linux system call table: – http://docs.cs.up.ac.za/programming/asm/derick_tut/syscalls.html • Operating system concepts(Galvin), chapter 2