Upload
imadpr
View
215
Download
0
Embed Size (px)
Citation preview
7/28/2019 unix-chap-2(7-2-12)_new
1/36
Ihr Logo
Unix&Network programming
"Study Of Multiuser Operating System and their Features
Course Instructor : K.JAVUBAR SATHICK
University : BSA University
7/28/2019 unix-chap-2(7-2-12)_new
2/36
Your Logo
Contents to be covered:
Process Environment
Main function
Process Termination.
Command-line arguments.
Environment List
Memory layout of C program in unix.
Memory Allocation
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
3/36
Your Logo
Introduction
In this chapter we examine the environment of a single process.
We also see how the main function is called when program is executed.
How command-line argument are passed to the new progam.
How the typical memory layout looks like.
How to allocate the additional memory.
How to use the environment variable.
Various ways for process to terminate.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
4/36
Your Logo
Main function
A c program starts execution with a function called main.
The prototype for the main function is int main(int argc, char *argv[]);
Where argc is the no. of command-line arguments and argv is an array
of pointers to the arguments.
When C program is executed by kernel -by any one of the exec fn.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
5/36
Your Logo
Process Termination
There are eight ways for a process to terminate.
Normal termination occurs in five ways.
Abnormal termination occurs in three ways.
Five normal termination ways are as follows,
1. Return from main fn.
2. Calling exit fn.
3. Calling _exit or _Exit fn.
4. Return of the last thread from its start routine.
5. Calling pthread_exit from the last thread.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
6/36
Your Logo
Process Termination
Abnormal termination occurs in three ways.
Three Abnormal termination ways are as follows,
1. Calling abort fn.
2. Receipt of signal.
3. Response of the last thread to cancellation request.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
7/36
Your Logo
Exit functions
Three functions terminate a program or process normally are as follow
_exit() and _exit() which returns to the kernel immediately,
and exit(), which performs certain clean up processing and then returns to
the kernel.
DEPARTMENT OF COMPUTER APPLICATIONS
#include // standard library header file
Void exit(int status); // performs clean up work
Void _Exit(int status);// no clean up work, returns im to ker
#include // unix standard library header file
Void _exit(int status);// no clean up work, returns im to ker
7/28/2019 unix-chap-2(7-2-12)_new
8/36
Your Logo
Command-Line arguments& Environment ListCommand-Line Argument:
The term command-line argument can be informally defined as anyparameter that is typed after the name of a program in a command
interpreter (such as a DOS box or Unix shell).
For example, if you typed the command rmfile.s here "file.s" is a
command-line argument which tells the program rm to remove the file "file.s".
This is the part of normal operation of the unix system shells.
Environment List:
Each program is also passed an environment list, like the argument list.
The environment list is an array of character pointers, with each pointercontaining the address of a null-terminated c string.
The address of the array of pointers is contained in the global variable
environ: extern char ** environ
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
9/36
Your Logo
Environment List
environment ptr environment list environment string
Environ: HOME=/home/sar\0
PATH=/bin:/usr/bin\0
SHELL=/bin/bash\0
USER=sar\0
LOGNAME=sar\0
ENVIRONMENT CONSISTING OF FIVE C CHARACTER STRINGS
DEPARTMENT OF COMPUTER APPLICATIONS
NULL
7/28/2019 unix-chap-2(7-2-12)_new
10/36
Your Logo
Memory layout of c programThe memory layout of C program as the following segments
1. Text Segment.
2. Intialized data segment.
3. Unintialized data segment.
4.Stack.
5.Heap.
1. Text Segment:
This segment as machine instruction that the cpu executes.
Usually, the text segment is sharable so that only a single copy needs to bein memory for frequently executed programs such as c compiler, the shellso on....
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
11/36
Your Logo
Memory layout of c program2. Intialized data segment:
This segment usually called simply the data segment, containing variablesthat are specifically initialized in the program. For eg int maxcount=35;
3. Uninitialized data segment:
This segment often called as the bss segment block started by symbol.
Data in this segment are initialized by the kernel before the program startsexecuting.
4. Stack:
In this segment, the automatic variables are stored, along with informationthat is saved each time when the function is called.
The space for automatic and temporary variable is stored on the stack.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
12/36
Your Logo
Typical Memory Arrangement5. Heap:
In this segment dynamic memory allocation usually takes place.
And the heap is located between uninitialized data segment and stacksegment.
high address command-line agr and env. Var
initialized to zero by execread from program file by
exec
Low address
DEPARTMENT OF COMPUTER APPLICATIONS
Stack
heap
Uninitialized data
Initialized data
text
7/28/2019 unix-chap-2(7-2-12)_new
13/36
Your Logo
Memory AllocationThree functions is used for Memory allocation;
1. Malloc: which allocates the specified no. Of bytes of memory. The initialvalue of the memory is indeterminate.
2. Calloc: which allocates space for a specified no.of objects of a specified
size. The space is initialized to all 0 bits.3. Realloc: Which increase or decrease the size of previously allocatedmemory.
DEPARTMENT OF COMPUTER APPLICATIONS
#include
Void *malloc(size_t size);
Void *calloc(size_t nobj,size_t size);Void *realloc(void* ptr,size_t newsize);
Void free(void * ptr);
7/28/2019 unix-chap-2(7-2-12)_new
14/36
Your Logo
Process controlContents to be covered;
Process Identifier.
Fork function.
Vfork function.
Wait and wait pid function.
Race condition.
Six exec function.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
15/36
Your Logo
Process control-process identifier Every process has unique process id.
Unique pid can be reused, once a process terminates their ids become
candidates for reusability.
This prevents a new process from being mistakenly referred again.
Pid with 0 is scheduler process and it is often referred as swapper.
In addition to the process id,there are other identifier for every process they are
as follows,
A. pid_t getpid(void) // process id of the calling process.
B. pid_t getppid(void) //parent process id of the calling process.
C. uid_t getuid(void) //real user id of the calling process.
D. uid_t geteuid(void) // effective user id of the calling process so on
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
16/36
Your Logo
Fork function An existing process can create a new process by calling the function known as
fork which is syntactically referred as Pid_t fork(void);
It creates a new process called child process.
It returns 2values : 1st value throws 0 for child process which indicates
that process can have only single parent process. 2nd value throws pid ofthe child process for parent process the reason is process can have more
than one child.
Reason for 0 in child process is child can have only one parent.
Child process can always call getppid to obtain the pid of its parent.
The child process is copy of parent.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
17/36
Your Logo
Vfork function & wait and wait pid function Same calling sequence as that of fork function.
The vfork function is intended to create new process when the purpose ofnew process is to exec a new program.
It creates a new process without copying the address space of parent
into child.Wait & wait pid fn:
When a process terminates either normally or abnormally, the kernelnotifies the parent process by sending the SIGCHILD signal to the parent.
Because the child process termination is asynchronous event.so parentmight ignore this signal or it can be handled.
Ifit decides to handle then parent might call wait and waitpid fn.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
18/36
Your Logo
wait and wait pid function Role of wait and waitpid fn:
It blocks all the child process which are still running.
Returns immediately with termination status of the child.
Returns immediately with an error.
DEPARTMENT OF COMPUTER APPLICATIONS
#include
pid_t wait(int *statloc);
pid_t waitpid(pid_pid, int *statloc,int options);
7/28/2019 unix-chap-2(7-2-12)_new
19/36
Your Logo
Difference between wait and wait pid function The wait fn can block the caller until a child process terminates,
whereas waitpid prevents it from blocking.
The waitpid does not wait for the child that terminates first.
features of waitpid fn:
1. the waitpid fn let us wait for one particular process,whereas wait fnwill return the status of any terminated child.
2. the waitpid fn provides the non-blocking version of wait.
3. the waitpid fn provides support for job control.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
20/36
Your Logo
Race condition/ Exec fn This race condition occurs when multiple processes are trying to do
some work with shared data and final outcome depends on order inwhich process run.
Fork fn initiates race condition because parent and child processcompetes.
Six Exec fn:
The exec function is used for execution of the process.
When a process calls one of the exec functions, that process iscompletely replaced by the new program starts executing at its main
function.
The process Id does not change across an exec, because a newprocess is not created; exec merely replaces the current process-itstext,data,heap and stack segments with a brand new program fromdisk.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
21/36
Your Logo
Exec function #include
Int execl(const char* pathname, const char *arg0,./*(char *)0 */);
Int execv(const char *pathname, char *const argv[]);
Int execle(const char *pathname,const char *arg0,/* (char *) 0, char*const
envp[]*/);
Int execve(const char *pathname,char *const argv[], char *const envp[]);
Int execlp(const char *filename, const char *arg0,./* (char *) 0 */);
Int execvp(const char *filename, char *const argv[]);
1. The first difference in these fns is that the 1st four fn take a pathname
argumet,whereas the last 2 take a filename argument. When a filenameargument is specified,
2. If filename contains a slash, it is taken as a pathname, otherwise the executable
file is searched for in the dir specified by path environment variable.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
22/36
Your Logo
Relationship of six exec function
Only one of these 6 fns,execve is a system call within the kernel. The other 5 are
just library fn that eventually invoke this system call.
build argv build argv build argv
try each use
PATH environ
DEPARTMENT OF COMPUTER APPLICATIONS
execlp
execvp execv
execl
execve
(system call
Within the kernel)
execle
7/28/2019 unix-chap-2(7-2-12)_new
23/36
Your Logo
Features Of Unix Operating System Multitasking
Multitasking refers to OS that executes multiple tasks simultaneously.
UNIX refers to a task as a process.
A user can run several commands in background while executing anotherin the foreground.
When a background task is being executing, user can continue doing
another task
e.g., printing a large document can be performed in the background while
editing some other document in the foreground.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
24/36
Your Logo
Features Of Unix Operating System Multi-user OS
Multi-user refers to an OS that allows multiple users to use the system
simultaneously.
The theory of multi-user system is to approach 100% computer utilization
while reducing the cost per user.
A single user cannot use the printer, disk, memory or CPU 100% of the
time. But multiple users can increases the use of these devices and
resources by having an OS that manages the resources for them.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
25/36
Your Logo
Features Of Unix Operating System Portability
UNIX is highly portability is the ability of the software operating on one machine
to operating as efficiently on another, different machine.
Job Control
Job Control on UNIX refers to the ability to control which job is executed in the
foreground, background or is suspended.
Using Job control can increase the productivity of a user by allowing multiple
tasks to be juggled back and forth between background, foreground andsuspended states.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
26/36
Your Logo
Features Of Unix Operating System Hierarchical Structure
UNIX uses a hierarchical structure to store and maintain files. This structure
allows maximum flexibility for storing information to resemble its real life
structure. Multiple users may be grouped by corporate departments
The UNIX Shell
The shell is a very powerful and dynamic UNIX utility. It is the primary interface
to the OS (kernel). It can be interactively programmed or it can be used to write
scripts to solve simple to complex problem.
Pipes and Filters
Pipes and filters contribute to the power of UNIX. These enable several
commands or utilities to be combined to perform complex functions.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
27/36
Your Logo
Features Of Unix Operating System
Device Independence
UNIX system considers all devices connected to it as files. It hides the machine
architecture from the users, making it easier to write programs that run on
different hardware implementations.
System Security
Being a multi-user OS, UNIX offers protection to one users information from the
user without permission i.e., Invalid users cannot access data, making it easier
to write programs that run on different hardware implementations.
Communication
The UNIX system has several built in programs, enabling the user to
communicate, transfer files across different UNIX systems and between UNIX
and other OS system.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
28/36
Your Logo
Features Of Unix Operating System
Programming Capability
UNIX is a highly programmable operating system.
UNIX facilities the user to develop both system and application programs.
Programming in UNIX is of two types they are Shell programming andProgramming in language (Like C, C++, Java, etc).
The programs written in shells are called as Shell files
The command statements in the programs are called as shell Script.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
29/36
Your Logo
Unix System Overview Logging in:
we log in with the name and password where password will be read by the
internal components of os such as kernel,shell etc.
home/mcaii/myfolder
Files &Directories:
File system is a hierarchial arrangements of directories and files.
Directory is a file that contains directory entries.
Some of the attributes of files are 1. type of file,2. size of file,3.owner of thefile,4. permission for file accessing so on
The stat and fstat functions return a structure of information containing all the
attributes of a file.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
30/36
Your Logo
Unix System Overview
File Name: Name in a directory which is used refer the file is called as Filename.
Path Name:A sequence of one or more file names separated by slash can be
referred as path name. A path name begin with a slash is often called as
absolute pathname or relative path name.
Working & Home directory: Every process as working directory.Some times
referred as current working directory(CWD). When we login, the working
directory is set to our home directory. It is obtained when we enter a password.
Program & Processes:A program is an executable file residing on the disk in a
directory. An executing instance of program is often referred as process. Every
process is referred by the unique ID called process id and it is a non-negativeinteger.
Process Control: There are 3 primary functions is used for process control they
are fork.exec and waitpid.
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
31/36
Your Logo
File I/O
Most of the file I/O on unix system can be performed using only five functions:
Open
Read
Write
lseek
and close
File Descriptor: It is denoted by fd
To the kernel, all open files are referred to by File descriptors. A file descriptor is
a non-negative integer.
When we open an existing file or create a new file,the kernel returns a file
descriptor to the process
When we want to read or write a file. we identify the file with fd that was
returned by open or creat fn as an argument to either read or write
DEPARTMENT OF COMPUTER APPLICATIONS
7/28/2019 unix-chap-2(7-2-12)_new
32/36
Your Logo
File I/O Open Function:
A file is opened or created by calling the open function
The pathname is name of the file to open or create.
The oflag argument is combination of one or more following operations which is
controlled by the header.
O_RDONLY -open for reading only.
O_WRONLY -open for writing only. ONE OF THESE 3 CONSTANTS
O_RDWR -open for reading and writing. MUST BE SPECIFIED.
DEPARTMENT OF COMPUTER APPLICATIONS
#include
int open(const char *pathname,int oflag/*mode_t mode*/);returns file descriptor if OK,-1 on error
7/28/2019 unix-chap-2(7-2-12)_new
33/36
Your Logo
File I/O The following constants are optional
O_APPEND,O_CREAT,O_EXCL,O_TRUNC,O_NOCTTY and O_NONBLOCK
Creat Function:
A new file can also be created by calling the creat fn.
DEPARTMENT OF COMPUTER APPLICATIONS
#include
int creat(const char *pathname,mode_t mode);
returns file descriptor opened for writing only if OK,-1 on error
7/28/2019 unix-chap-2(7-2-12)_new
34/36
Your Logo
File I/O Close Function:
An open file is closed by calling the close fn.
Lseek Function:
Every open file has an associated current file offset, normally a non
negative integer that measures the number of bytes from beginning of thefile.
An open files offset can be set explicitly by calling lseek fn.
DEPARTMENT OF COMPUTER APPLICATIONS
#include
int close(int filedes);Returns:0 if OK,-1 on error
7/28/2019 unix-chap-2(7-2-12)_new
35/36
Your Logo
File I/O
The interpretation of the offset depends on the value of the whence argument.
If the whence is SEEK_SET,the files offset is set to offset bytes from
beginning of the file.
If the whence is SEEK_CUR,the files offset is set to its current value plusthe offset.
If the whence is SEEK_END,the files offset is set to the size of the file plus
the offset.
DEPARTMENT OF COMPUTER APPLICATIONS
#include
off_t lseek(int filedes,off_t offset,int whence);
Returns: new file offset if OK,-1 on error
7/28/2019 unix-chap-2(7-2-12)_new
36/36
Your Logo
File I/ORead function:
Data is read from open file with read function.
Write Function:
Data is written to an open file with write function
DEPARTMENT OF COMPUTER APPLICATIONS
#include
ssize_t read(int filedes, void *buf, size_t nbytes);
Returns:no of bytes read,0 if eof,-1 on error
#include
ssize_t write(int filedes, const void *buf, size_t nbytes);Returns:no of bytes written if OK,-1 on error