syedmustafablr
8,841 views
178 slides
Mar 15, 2016
Slide 1 of 291
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
About This Presentation
6th semester Unix System Programming
Size: 4.29 MB
Language: en
Added: Mar 15, 2016
Slides: 178 pages
Slide Content
UNIX SYSTEM PROGRAMMING
BY
PROF. A. SYED MUSTAFA
HKBK COLLEGE OF ENGINEERING
1.Function prototyping
2.Support of the constand volatile data type qualifiers.
3.Support wide characters and internationalization.
4.Permit function pointers to be used without dereferencing.
The major differences between ANSI C and K&R C
[Kernighan and Ritchie] are as follows:
2PROF. SYED MUSTAFA, HKBKCE
1.Function prototyping
ANSICadoptsC++functionprototypetechniquewherefunctiondefinitionanddeclarationinclude
functionnames,arguments’datatypes,andreturnvaluedatatypes.
ThisenablesANSICcompilerstocheckforfunctioncallsinuserprogramsthatpassinvalidnumberof
argumentsorincompatiblearguments’datatype.
ThesefixamajorweaknessofK&RCcompilers:invalidfunctioncallsinuserprogramsoftenpass
compilationbutcauseprogramstocrashwhentheyareexecuted.
Eg:unsigned long demo(char * fmt, double data)
{
/*body of demo*/
}
External declaration of this function demo is
unsigned long demo(char * fmt, double data);
eg:intprintf(constchar* fmt,...........); specify variable number of arguments
The major differences between ANSI C and K&R C
[Kernighan and Ritchie] are as follows:
3PROF. SYED MUSTAFA, HKBKCE
2. Support of the constand volatile data type qualifiers
The constkeyword declares that some data cannot be changed.
Eg:intprintf(constchar* fmt,...........);
Declaresafmtargumentthatisofaconstchar*datatype,meaningthatthe
functionprintfcannotmodifydatainanycharacterarraythatispassedasanactual
argumentvaluetofmt.
The major differences between ANSI C and K&R C
[Kernighan and Ritchie] are as follows:
4PROF. SYED MUSTAFA, HKBKCE
2. Support of the constand volatile data type qualifiers
Volatilekeywordspecifiesthatthevaluesofsomevariablesmaychange
asynchronously,givinganhinttothecompiler’soptimizationalgorithmnotto
removeany“redundant”statementsthatinvolve“volatile”objects.
eg:
char get_io()
{
volatile char* io_port= 0x7777;
char ch= *io_port;/*read first byte of data*/
ch= *io_port;/*read second byte of data*/
}
If io_portvariable is not declared to be volatile when the program is compiled, the
compiler may eliminate second ch= *io_portstatement, as it is considered
redundant with respect to the previous statement.
The major differences between ANSI C and K&R C
5PROF. SYED MUSTAFA, HKBKCE
3. Support wide characters and internationalization
•ANSICsupportsinternationalisationbyallowingC-programtousewide
characters.Widecharactersusemorethanonebyteofstoragepercharacter.
•ANSICdefinesthesetlocalefunction,whichallowsuserstospecifytheformatof
date,monetaryandrealnumberrepresentations.
•Foreg:mostcountriesdisplaythedateindd/mm/yyyyformatwhereasUS
displaysitinmm/dd/yyyyformat.
Functionprototypeofsetlocalefunctionis:
#include<locale.h>
charsetlocale(intcategory,constchar*locale);
The major differences between ANSI C and K&R C
6PROF. SYED MUSTAFA, HKBKCE
3. Support wide characters and internationalization
The major differences between ANSI C and K&R C
The setlocalefunction prototype and possible values of the category argument are declared in the
<locale.h> header. The category values specify what format class(es) is to bechanged.
Some of the possible values of the category argumentare:
CategoryValue Effect on standard C functions/macros
LC_CTYPE ⇒Affects behavior of the <ctype.h> macros
LC_TIME ⇒Affects date and time format.
LC_NUMERIC ⇒Affects number representation format
LC_MONETARY ⇒Affects monetary values format
LC_ALL ⇒combines the affect of all above
Eg: setlocale(LC_ALL, “C”);
7PROF. SYED MUSTAFA, HKBKCE
4. Permit function pointers to be used without dereferencing
ANSICspecifiesthatafunctionpointermaybeusedlikeafunctionname.No
referencingisneededwhencallingafunctionwhoseaddressiscontainedinthe
pointer.
ForExample:
extern void foo(double xyz,constint*ptr);
void (*funptr)(double,constint*)=foo;
The function can be called directly or through function pointer as given below:
foo(12.78,”Hello world”);
funptr(12.78,”Helloworld”);
K& R C requires funptrbe dereferenced to callfoo:
(* funptr) (13.48,”Hellousp”);
The major differences between ANSI C and K&R C
8PROF. SYED MUSTAFA, HKBKCE
#include<unistd.h>
long sysconf(constintlimit_name);
long pathconf(constchar *pathname, intflimit_name);
long fpathconf(constintfd, intflimit_name);
Limits checking at Runtime
9PROF. SYED MUSTAFA, HKBKCE
Limits checking at Runtime
The following test_config.Cillustrates the
use of sysconf, pathcongand fpathconf:
#define _POSIX_SOURCE
#define _POSIX_C_SOURCE199309L
#include<stdio.h>
#include<iostream.h>
#include<unistd.h>
intmain()
{
intres;
if((res=sysconf(_SC_OPEN_MAX))==-1)
perror(“sysconf”);
else
cout<<”OPEN_MAX:”<<res<<endl;
if((res=pathconf(“/”,_PC_PATH_MAX))==-1)
perror(“pathconf”);
else
cout<<”max path name:”<<(res+1)<<endl;
if((res=fpathconf(0,_PC_CHOWN_RESTRICTED))==-1)
perror(“fpathconf”);
else
cout<<”chown_restrictedfor stdin:”<<res<<endl;
return 0;
}
10PROF. SYED MUSTAFA, HKBKCE
The POSIX.1 FIPSStandard
FIPS stands for Federal Information Processing Standard. The FIPS standard is a restriction of the
POSIX.1 –1988 standard, and it requires the following features to be implemented in all FIPS-
conformingsystems:
Job control
Saved set-UID and savedset-GID
Long path name is notsupported
The _POSIX_CHOWN_RESTRICTED must bedefined
The _POSIX_VDISABLE symbol must bedefined
The NGROUP_MAX symbol’s value must be at least8
The read and write API should return the number of bytes that have been transferred after the
APIs have been interrupted bysignals
The group ID of a newly created file must inherit the group ID of its containing directory
11PROF. SYED MUSTAFA, HKBKCE
The X/OPEN Standards
The X/Open organization was formed by a group of European companies to
propose a common operating system interface for their computer systems.
The portability guides specify a set of common facilities and C application
program interface functions to be provided on all UNIX based open systems.
In 1973, a group of computer vendors initiated a project called “common
open software environment” (COSE). The goal of the project was to define a
single UNIX programming interface specification that would be supported
by all type vendors.
The applications that conform to ANSI C and POSIX also conform to the
X/Open standards but not necessarily vice-versa.
12PROF. SYED MUSTAFA, HKBKCE
UNIX AND POSIX APIs
API -A set of application programming interface functions that can be called
by user programs to perform system specific functions.
Most UNIX systems provide a common set of API’s to perform the following
functions.
13PROF. SYED MUSTAFA, HKBKCE
API Common Characteristics
ManyAPIsreturnsanintegervaluewhichindicatesthetermination
statusoftheirexecution
APIreturn-1toindicatetheexecutionhasfailed,andtheglobalvariable
errnoissetwithanerrorcode.
auserprocesmaycallperror()functiontoprintadiagnosticmessageof
thefailuretothestdo/p,or
itmaycallstrerror()functionandgivesiterrnoastheactualargument
value;thestrerrorfunctionreturnsadiagnosticmessagestringand
theuserprocessmayprintthatmessageinitspreferredway
thepossibleerrorstatuscodesthatmaybeassignedtoerrnobyanyAPI
aredefinedinthe<errno.h>header.
14PROF. SYED MUSTAFA, HKBKCE
UNIT 2 -UNIX FILES
Files are the building blocks of any operating system.
File Types
A file in a UNIX or POSIX system may be one of the following types:
•Regular file
•Directory file
•FIFO file
•Character device file
•Block device file
16PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
•Regular file
A regular file may be either a text file or a binary file
These files may be read or written to by users with the appropriate access permission
Regular files may be created, browsed through and modified by various means
such as text editors or compilers, and they can be removed by specific system
commands
17PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
•Directory file
It is like a folder that contains other files, including sub-directory files.
It provides a means for users to organisetheir files into some hierarchical structure
based on file relationship or uses.
Ex: /bin directory contains all system executable programs, such as cat, rm, sort
A directory may be created in UNIX by the mkdircommand
Ex: mkdir/usr/foo/xyz
A directory may be removed via the rmdircommand
Ex: rmdir/usr/foo/xyzThecontent of directory may be displayed by the
ls command
18PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
•Device file
oFor block device file, use argument ‘b’ instead of‘c’.
19PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
FIFO file
It is a special pipe device file which provides a temporary buffer for two or more processes to
communicate by writing data to and reading data from thebuffer.
The size of the buffer is fixed toPIPE_BUF.
Data in the buffer is accessed in a first-in-first-outmanner.
The buffer is allocated when the first process opens the FIFO file for read orwrite
Thebufferisdiscardedwhenallprocessesclosetheirreferences(streampointers)totheFIFOfile.
Data stored in a FIFO buffer istemporary.
A FIFO file may be created via the mkfifocommand.
oThe following command creates a FIFO file
mkfifo/usr/d1/myfifo
mknod/usr/d1/myfifop
FIFO files can be removed using rmcommand.
21PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
Symbolic link file
BSD UNIX & SV4 defines a symbolic linkfile.POSIX.1 does not support symbolic link filetype
A symbolic link file contains a path name which references another file in either local or a remote file
system.
A symbolic link may be created in UNIX via the lncommand
Ex: ln-s/usr/d1/f1 /usr/d2/f2
It is possible to create a symbolic link to reference another symboliclink.
rm, mv and chmodcommands will operate only on the symbolic link arguments directly and not on the files
that theyreference.
22PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
TheUNIXandPOSIXFileAttributes
Thegeneralfileattributesforeachfileinafilesystemare:
9)Lastaccesstime-thetime,thefilewaslastaccessed.
10)Lastmodifiedtime-thefile,thefilewaslastmodified.
11)Lastchangetime-thetime,thefilewaslastchanged.
12)MajorNumber
13)MinorNumber
Theattributesthatareconstantandcannotbechangedforanyfileare:
Filetype
File inodenumber
File systemID
Major and minor devicenumber
26PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
27PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
InUNIXsystemV,afilesystemhasaninodetable,whichkeepstracksofallfiles.
Eachentryoftheinodetableisaninoderecordwhichcontainsalltheattributes
ofafile,includinginodeno.andthephysicaldiskaddresswheredataofthefileis
stored
For any operation, if a kernel needs to access information of a file with an inode
no. 15, it will scan the inodetable to find an entry, which contains an inodeno.
15 in order to access the necessarydata.
An inodeno is unique within a file system.
A file inoderecord is identified by a file system ID and an inodeno.
Inodesin UNIX SystemV
28PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
Application Programming Interface to Files
Files are identified by pathnames.
Files should be created before they can be used.
The various commands and system calls to create files are
Filetype commands Systemcall
Regular file
Directory file
FIFO file
Devicefile
Symbolic linkfile
vi,pico,emac
mkdir
mkfifo
mknod
ln–s
open,creat
mkdir,
mknodmkfifo,
mknod
Symlink
31PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
UNIX Kernel Support for Files
InUNIXsystemV,thekernelmaintainsafiletablethathasanentryof
allopenedfilesandalsothereisaninodetablethatcontainsacopyof
fileinodesthataremostrecentlyaccessed.
Aprocess,whichgetscreatedwhenacommandisexecutedwillbe
havingitsowndataspace(datastructure)whereinitwillbehavingfile
descriptortable.
ThefiledescriptortablewillbehavinganmaximumofOPEN_MAXfile
entries.
Whenevertheprocesscallstheopenfunctiontoopenafiletoreador
write,thekernelwillresolvethepathnametothefileinodenumber.
35PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
UNIX Kernel Support for Files
Data Structure for FileManipulation 36PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
UNIX Kernel Support for Files
Thestepsinvolvedare:
1.Thekernelwillsearchtheprocessfiledescriptortableand
lookforthefirstunusedentry.
2.Ifanentryisfound,thatentrywillbedesignatedto
referencethefile.Theindexoftheentrywillbereturnedto
theprocessasthefiledescriptoroftheopenedfile.
3.Thekernelwillscanthefiletableinitskernelspacetofind
anunusedentrythatcanbeassignedtoreferencethefile.
37PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
UNIX Kernel Support for Files
Ifanunusedentryisfoundthefollowingeventswilloccur:
1.Theprocessfiledescriptortableentrywillbesettopointtothisfile
tableentry.
2.Thefiletableentrywillbesettopointtotheinodetableentry,where
theinoderecordofthefileisstored.
3.Thefiletableentrywillcontainthecurrentfilepointeroftheopenfile.
Thisisanoffsetfromthebeginningofthefilewherethenextreador
writewilloccur.
4.Thefiletableentrywillcontainanopenmodethatspecifiesthatthe
fileopenedisforreadonly,writeonlyorreadandwriteetc.This
shouldbespecifiedinopenfunctioncall.
38PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
UNIX Kernel Support for Files
Ifanunusedentryisfoundthefollowingeventswilloccur:
5.Thereferencecount(rc)inthefiletableentryissetto1.Referencecount
isusedtokeeptrackofhowmanyfiledescriptorsfromanyprocessare
referringtheentry.
6.Thereferencecountofthein-memoryinodeofthefileisincreasedby1.
Thiscountspecifieshowmanyfiletableentriesarepointingtothat
inode.
If either (1) or (2) fails, the open system call returns -1 (failure/error)
39PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
UNIX Kernel Support for Files
Normally the reference count in the file table entry is 1, if we wish to increase the rcin the
file table entry, this can be done using fork,dup,dup2 system call.
When a open system call is succeeded, its return value will be an integer (file descriptor).
Whenever the process wants to read or write data from the file, it should use the file
descriptor as one of its argument.
40PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
UNIX Kernel Support for Files
The following events will occur whenever a process calls the close function to close
the files that are opened.
1.The kernel sets the corresponding file descriptor table entry to be unused.
2.It decrements the rcin the corresponding file table entry by 1, if rcnot equal to 0 go to
step 6.
3. The file table entry is marked as unused.
4. The rcin the corresponding file inodetable entry is decremented by 1, if rcvalue not
equal to 0. go to step 6.
5. If the hard link count of the inodeis not zero, it returns to the caller with a success status
otherwise it marks the inodetable entry as unused and de-allocates all the physical dusk
storage of the file.
6. It returns to the process with a 0 (success) status.
41PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
Relationship of C Stream Pointers and File Descriptors
The major difference between the stream pointer and the file descriptors are as
follows:
42PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
Relationship of C Stream Pointers and File Descriptors
C libraryfunction UNIX system callused
fopen open
fread, fgetc, fscanf,fgets read
fwrite, fputc, fprintf,fputs write
fseek, fputc, fprintf,fputs lseek
fclose close
The file descriptor associated with a stream pointer can be extracted by filenomacro, which is
declared in the<stdio.h> header.
intfileno(FILE * stream_pointer);
To convert a file descriptor to a stream pointer, we can use fdopenC library function
FILE *fdopen(intfile_descriptor, char * open_mode);
The following lists some C library functions and the underlying UNIX APIs they use to perform their
functions:
43PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
Directory Files
It is a record-oriented file.
Each record contains the information of a file residing in that directory
The record data type is structdirentin UNIX System V and POSIX.1 and
structdirect in BSD UNIX.
The record content is implementation-dependent
They all contain 2 essential member fields:
1.File name
2.Inodenumber
Usage is to map file names to corresponding inodenumber
:
44PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
Directory Files
: Directoryfunction Purpose
opendir Opens a directoryfile
readdir Reads next record from thefile
closedir Closes a directoryfile
rewinddir Sets file pointer to beginning offile
45PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
Hard and Symbolic Links
:
hard link is a UNIX pathname for a file. Generally most of the UNIX files will be
having only one hardlink.
In order to create a hard link, we use the commandln.
Example :
Consider a file /usr/ syed/f1, to this we can create a hard linkby
ln /usr/syed/f1 /usr/syed/f2
Symbolic link can be creates by the same command ‘ln’but
with option –s
Example: ln–s /usr/syed/f1/usr/syed/sf1
46PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
Hard and Symbolic Links
:
lncommanddiffersfromthecp(copy)commandinthatcp
createsaduplicatedcopyofafiletoanotherfilewithadifferent
pathname,
whereaslncommandcreatesanewlinktoreferenceafile.
47PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
Hard and Symbolic Links
:
Let’s visualize the content of a directory file after the execution of commandln.
Case 1: for hard linkfile
ln /usr/syed/abc/usr/mustafa/xyz
The content of the directory files/usr/syedand /usr/mustafaare:
48PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
Hard and Symbolic Links
:
Let’s visualize the content of a directory file after the execution of commandln.
Case 1: for hard linkfile
ln /usr/syed/abc/usr/mustafa/xyz
The content of the directory files/usr/syedand /usr/mustafaare:
Both /urs/syed/abcand /usr/mustafa/xyz refer to the same inode
number 201, thus no new file is created.
49PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
Hard and Symbolic Links
:
Case 2: For the same operation, if ln –s command is used then a new inodewill be
created.
ln –s/usr/syed/abc /usr/mustafa/xyz
The content of the directory files syedand mustafawill be
Ifcpcommandwasusedthenthedatacontentswillbeidenticalandthe2fileswill
beseparateobjectsinthefilesystem,whereasinln–sthedatawillcontainonly
thepathname.
50PROF. SYED MUSTAFA, HKBKCE
UNIT 2 UNIX FILES
Hard and Symbolic Links
:
Limitations of hard link:
User cannot create hard links for directories, unless he has super-user privileges.
User cannot create hard link on a file system that references files on a different file system,
because inodenumber is unique to a file system.
Differences between hard link and symbolic link are listed below:
51PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
A file in a UNIX or POSIX system may be one of the following
types:
•Regular file
•Directory file
•FIFO file
•Character device file
•Block device file
•Symbolic link file
There are special API’s to create these types of files
:
52PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
open
Thisisusedtoestablishaconnectionbetweenaprocessandafile
i.e.itisusedtoopenanexistingfilefordatatransferfunctionorelseit
maybealsobeusedtocreateanewfile.
Thereturnedvalueoftheopensystemcallisthefiledescriptor(row
numberofthefiletable),whichcontainstheinodeinformation.
The prototype of open function is
#include<sys/types.h>
#include<sys/fcntl.h>
intopen(constchar *pathname, intaccessmode, mode_tpermission);
:
53PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
open
Ifsuccessful,openreturnsanonnegativeintegerrepresentingtheopen
filedescriptor.Ifunsuccessful,open()returns–1.
Thefirstargumentisthenameofthefiletobecreatedoropened.
Thismaybeanabsolutepathnameorrelativepathname.
Ifthegivenpathnameissymboliclink,theopenfunctionwillresolve
thesymboliclinkreferencetoanonsymboliclinkfiletowhichitrefers.
Thesecondargumentisaccessmodes,whichisanintegervaluethat
specifieshowactuallythefileshouldbeaccessedbythecallingprocess.
: 54PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
open
Generally the access modes are specified in <fcntl.h>.
Various access modes are:
There are other access modes, which are termed as access modifier flags,
and one or more of the following can be specified by bitwise-ORingthem
with one of the above access mode flags to alter the access mechanism of
the file.
Sl. NoFlag Meaning
1O_RDONLYopen for reading file only
2O_WRONLYopen for writing file only
3O_RDWR opens for reading and writing file
55PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
open
access modifier flags
S.No Flag Meaning
1O_APPEND Append data to the end of file.
2O_CREAT Create the file if it doesn’t exist
3O_EXCL Generate an error if O_CREAT is also specified and the
file already exists.
4O_TRUNC If file exists discard the file content and set the file
size to zero bytes.
5O_NONBLOCK Specify subsequent read or write on the file should be
non-blocking.
6O_NOCTTY Specify not to use terminal device file as the calling
process controlterminal.
56PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
open
To illustrate the use of the above flags, the following example statement opens
a file called /usr/syed/uspfor read and write in append mode:
intfd=open(“/usr/syed/usp”, O_RDWR | O_APPEND,0);
If the file is opened in read only, then no other modifier flags can be used.
If a file is opened in write only or read write, then we are allowed to use any
modifier flags along with them.
The third argument is used only when a new file is being created.
57PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
open
58PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
open
59PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
open
60PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
open
To open "sample.txt" in the current working directory for appending or create it, if it
does not exist, with read, write and execute permissions for owner only:
fd= open(“sample.txt", O_WRONLY|O_APPEND|O_CREAT, S_IRWXU);
fd= open(“sample.txt", O_WRONLY|O_APPEND|O_CREAT, 0700);
fd= open(“sample.txt", O_WRONLY|O_CREAT|O_EXCL,
S_IRWXU|S_IROTH|S_IWOTH);
fd= open(“sample.txt", O_WRONLY|O_CREAT|O_EXCL,0706);
fd= open(“sample.txt", O_WRONLY|O_CREAT|O_TRUNC,0706 );
61PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
open
Tag Description
EACCES Therequestedaccesstothefileisnotallowed,orsearch
permissionisdeniedforoneofthedirectoriesinthepath
prefixofpathname,orthefiledidnotexistyetandwrite
accesstotheparentdirectoryisnotallowed.
EEXIST pathnamealreadyexistsandO_CREAT andO_EXCL were
used.
EFAULT pathnamepointsoutsideaccessibleaddressspace.
ENOENT O_CREATisnotsetandthenamedfiledoesnotexist.Or,a
directorycomponentinpathnamedoesnotexistorisa
danglingsymboliclink.
ENOMEM Insufficientkernelmemorywasavailable.
62PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
creat( )
•This system call is used to create new regular files.
#include <sys/types.h>
#include<unistd.h>
intcreat(constchar *pathname, mode_tmode);
•Returns: file descriptor opened for write-only if OK, -1 on error.
•The first argument pathname specifies name of the file to be created.
•The second argument mode_t, specifies permission of a file to be
accessed by owner group and others.
•The creatfunction can be implemented using open function as:
#define creat(path_name, mode)
open (pathname, O_WRONLY | O_CREAT | O_TRUNC, mode);
63PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
read ( )
There are several cases in which the number of bytes actually read is less than
the amount requested:
Whenreadingfromaregularfile,iftheendoffileisreachedbeforethe
requestednumberofbyteshasbeenread.
Forexample,if30bytesremainuntiltheendoffileandwetrytoread100
bytes,readreturns30.Thenexttimewecallread,itwillreturn0(endoffile).
Whenreadingfromaterminaldevice.Normally,uptoonelineisreadata
time.
Whenreadingfromanetwork.Bufferingwithinthenetworkmaycauseless
thantherequestedamounttobereturned.
WhenreadingfromapipeorFIFO.Ifthepipecontainsfewerbytesthan
requested,readwillreturnonlywhatisavailable.
65PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
read ( )-Errors
Tag Description
EAGAIN
Non-blocking I/O has been selected usingO_NONBLOCK and no data
was immediately available for reading.
EBADF fdis not a valid file descriptor or is not open for reading.
EFAULT bufis outside your accessible address space.
EINTR The call was interrupted by a signal before any data was read.
EINVAL
fdis attached to an object which is unsuitable for reading; or the file
was opened with theO_DIRECT flag, and either the address specified
inbuf, the value specified incount, or the current file offset is not
suitably aligned.
EIO
I/O error. This will happen for example when the process is in a
background process group, tries to read from its controlling tty, and
either it is ignoring or blocking SIGTTIN or its process group is
orphaned. It may also occur when there is a low-level I/O error while
reading from a disk or tape.
EISDIR fdrefers to a directory.
66PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
write( )
The write system call is used to write data into a file
The write function puts data to a file in the form of fixed block size referred by a
given file.
Theprototypeofreadfunctionis:
#include<sys/types.h>
#include<unistd.h>
ssize_twrite(intfdesc, constvoid *buf, size_tsize);
If successful, write returns the number of bytes actually written.
If unsuccessful, write returns –1.
The first argument, fdescis an integer that refers to an opened file.
The second argument, bufis the address of a buffer that contains data to be written.
The third argument, size specifies how many bytes of data are in the bufargument.
The return value is usually equal to the number of bytes of data successfully written to a file.
(size value)
68PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
write( )-Errors
Error Code Description
EAGAIN Non-blocking I/O has been selected usingO_NONBLOCK and the write would block.
EBADF fdis not a valid file descriptor or is not open for writing.
EFAULT bufis outside your accessible address space.
EFBIG An attempt was made to write a file that exceeds the implementation-defined
maximum file size or the process’ file size limit, or to write at a position past the
maximum allowed offset.
EINTR The call was interrupted by a signal before any data was written.
EINVAL fdis attached to an object which is unsuitable for writing; or the file was opened with
theO_DIRECT flag, and either the address specified inbuf, the value specified
incount, or the current file offset is not suitably aligned.
EIO A low-level I/O error occurred while modifying the inode.
EPIPE fdis connected to a pipe or socket whose reading end is closed. When this happens
the writing process will also receive aSIGPIPEsignal. (Thus, the write return value is
seen only if the program catches, blocks or ignores this signal.)
69PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIswrite( )
#include<fcntl.h>
intmain()
{
intfd,nob;charc[]=“ This is sample text”;
fd=open(“sample”,O_WRONLY,0777);
nob= write(fd,c,strlen(c));
if(nob!=-1)
printf(“Successfully written to file”);
else
perror(“write Error”);
close(fd);
return 0;
}
70PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
close( )
The close system call is used to terminate the connection to a file from a
process.
The prototype of the close() is
#include<unistd.h>
intclose(intfdesc);
If successful, close returns 0.
If unsuccessful, close returns –1.
The argument fdescrefers to an opened file.
Close function frees the unused file descriptors so that they can be reused to reference other
files. This is important because a process may open up to OPEN_MAX files at any time and
the close function allows a process to reuse file descriptors to access more than OPEN_MAX
files in the course of its execution.
The close function de-allocates system resources like file table entry and memory buffer
allocated to hold the read/write.
71PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
close( )-Errors
Tag Description
EBADF fdisn’t a valid open file descriptor.
EINTR Theclose() call was interrupted by a signal.
EIO An I/O error occurred.
72PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
75PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
76PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
77PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
78PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
79PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
80PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
81PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
82PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
83PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
84PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
85PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
86PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
Chown(), fchown(), lchown()
The chownfunctions changes the user ID and group ID of files.
The prototypes of these functions are:
#include<unistd.h>
#include<sys/types.h>
intchown(constchar *path_name, uid_tuid, gid_tgid);
intfchown(intfdesc, uid_tuid, gid_tgid);
intlchown(constchar *path_name, uid_tuid, gid_tgid);
The path_nameargument is the path name of a file.
The uidargument specifies the new user ID to be assigned to the file.
The gidargument specifies the new group ID to be assigned to the file.
87PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
Chown(), fchown(), lchown()
/* Program to illustrate chown() */
#include<iostream.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<pwd.h>
intmain(intargc, char *argv[ ])
{
if(argc>3)
{
cerr<<”usage:”<<argv[0]<<”<usr_name><
file>....\n”;
return 1;
}
structpasswd*pwd= getpwuid(argv[1]) ;
uid_tUID = pwd? pwd-> pw_uid: -1 ;
structstatstatv;
if (UID == (uid_t)-1)
cerr<<“Invalid user name”;
else
for (inti= 2; i< argc; i++)
if (stat(argv[i], &statv)==0)
{
if (chown(argv[i], UID,statv.st_gid))
perror(“chown”);
}
return 0;
}
88PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
Chmod(), fchmod()
The chmodand fchmodfunctions change file access permissions for owner, group &
others as well as the set_UID, set_GIDand stickyflags.
A process must have the effective UID of either the super-user/owner of thefile.
The prototypes of these functionsare
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
intchmod(constchar *pathname, mode_tflag);
intfchmod(intfdesc, mode_tflag);
89PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
FileandRecordLocking
The prototype of fcntlis
#include<fcntl.h>
intfcntl(intfdesc, intcmd_flag, ...);
The first argument specifies the file descriptor.
The second argument cmd_flagspecifies what operation has to be performed.
If fcntlis used for file locking then cmd_flagcan values as:
Cmd_flag Meaning
F_SETLK sets a file lock, do not block if this cannot succeed immediately
F_SETLKW sets a file lock and blocks the process until the lock is acquired
F_GETLK queries as to which process locked a specified region of file
104PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
FileandRecordLocking
For file locking purpose, the third argument to fctnlis an address of a struct
flock type variable.
This variable specifies a region of a file where lock is to be set, unset or
queried.
structflock
{
shortl_type; /* what lock to be set or to unlock file */
shortl_whence; /* Reference address for the next field */
off_tl_start; /*offset from the l_whencereference addr*/
off_tl_len; /*how many bytes in the locked region */
pid_tl_pid; /*pidof a process which has locked the file */
};
105PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
FileandRecordLocking
Thel_typefieldspecifiesthelocktypetobesetorunset.
Thepossiblevalues,whicharedefinedinthe<fcntl.h>header,and
theirusesare:
Thel_whence,l_start&l_lendefinearegionofafiletobelockedor
unlocked.
l_typevalue Use
F_RDLCK Set a read lock on a specified region
F_WRLCK Set a write lock on a specified region
F_UNLCK Unlock a specified region
106PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
FileandRecordLocking
Thepossiblevaluesofl_whenceandtheirusesare:
AlocksetbythefcntlAPIisanadvisorylockbutwecanalsousefcntlfor
mandatorylockingpurposewiththefollowingattributessetbeforeusingfcntl
1.Turn on the set-GID flag of the file.
2.Turn off the group execute right permission of the file.
l_whencevalue Use
SEEK_CUR The l_startvalue is added to current file pointer address
SEEK_END The l_startvalue is added to byte 0 of the file
SEEK_SET The l_startvalue is added to the end of the file
107PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
FileandRecordLocking
In the given example program, performed a read lock on a file “sample” from the 50th byte
to 150th byte.
#include<fcntl.h>
intmain ( )
{
intfd;
structflock lock;
fd=open(“sample”,O_RDONLY);
lock.l_type=F_RDLCK;
lock.l_whence=0;
lock.l_start=50;
lock.l_len=100;
fcntl(fd,F_SETLK,&lock);
}
108PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIsutime()
The utimefunction modifies the access time and the modification time stamps of a file.
The prototype of utimefunction is
#include<sys/types.h>
#include<unistd.h>
#include<utime.h>
intutime(constchar *path_name, structutimbuf*times);
•On success it returns 0, on failure it returns –1.
•The path_nameargument specifies the path name of a file.
•The times argument specifies the new access time and modification time for the file.
•The structutimbufis defined in the <utime.h> header as:
structutimbuf
{
}
time_t actime; /* access time*/
time_t modtime; /* modification time */
109PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
Directory File API’s
A Directory file is a record-oriented file, where each record stores a file name and the
inodenumber of a file that resides in that directory.
Directories are created with the mkdirAPI and deleted with the rmdirAPI.
The prototype of mkdiris
#include<sys/stat.h>
#include<unistd.h>
intmkdir(constchar *path_name, mode_tmode);
The first argument is the path name of a directory file to be created.
The second argument mode, specifies the access permission for the owner, groups
and others to be assigned to the file. This function creates a new empty directory.
The entries for “.” and “..” are automatically created.
The specified file access permission, mode, are modified by the file mode creation mask
of the process
111PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
Directory File API’s
To allow a process to scan directories in a file system independent manner, a directory
record is defined as structdirentin the <dirent.h> header for UNIX.
Some of the functions that are defined for directory file operations in the above header
are
#include<sys/types.h>
#if defined (BSD) && ! _POSIX_SOURCE
#include<sys/dir.h>
typedefstructdirect Dirent;
#else
#include<dirent.h>
typedefstructdirentDirent;
#endif
112PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
Directory File API’s
DIR *opendir(constchar *path_name);
Dirent*readdir(DIR *dir_fdesc);
intclosedir(DIR *dir_fdesc);
void rewinddir(DIR *dir_fdsec);
The uses of these functions are
Function Use
opendir
Opens a directory file for read-only. Returns a file handle dir * for future reference of
thefile.
readdir
Reads a record from a directory file referenced by dir-fdesc and returns that record
information.
rewinddir
Resets the file pointer to the beginning of the directory file referenced by dir-fdesc.
The next call to readdir will read the first record from thefile.
closedir closes a directory file referenced bydir-fdesc.
113PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
Directory File API’s
An empty directory is deleted with the rmdirAPI.
The prototype of rmdiris
#include<unistd.h>
intrmdir(constchar * path_name);
Ifthelinkcountofthedirectorybecomes0,withthecallandnootherprocesshasthe
directoryopenthenthespaceoccupiedbythedirectoryisfreed.
UNIXsystemshavedefinedadditionalfunctionsforrandomaccessofdirectoryfile
records.
Function Use
telldirReturns the file pointer of a givendir_fdesc
seekdirChanges the file pointer of a given dir_fdescto a specifiedaddress
114PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
Directory File API’s
The following list_dir.Cprogram illustrates the uses of the mkdir, opendir, readdir, closedir
and rmdirAPIs:
#include<iostream.h>
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<sys/stat.h>
#if defined(BSD) && !_POSIX_SOURCE
#include<sys/dir.h>
typedefstructdirect Dirent;
#else
#include<dirent.h>
typedefstructdirentDirent;
#endif
intmain(intagc, char* argv[])
{
Dirent* dp; DIR* dir_fdesc;
while(--argc>0)
{
if(!(dir_fdesc=opendir(*++argv)))
{
if(mkdir(*argv,S_IRWXU| S_IRWXG | S_IRWXO)==-1)
perror("opendir");
continue;
}
115PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
Directory File API’s
The following list_dir.Cprogram illustrates the uses of the mkdir, opendir, readdir, closedir
and rmdirAPIs:
for(inti=0;i<2;i++)
for(intcnt=0;dp=readdir(dir_fdesc);)
{
if(i)
cout<<dp->d_name<<endl;
if(strcmp(dp->d_name,".") &&
strcmp(dp->d_name,".."))
cnt++;
}
if(!cnt)
{
rmdir(*argv);
break;
}
rewinddir(dir_fdesc);
} //end for
closedir(dir_fdesc);
} //end while
} //end main
116PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
Device file APIs
Thefirstargumentpathnameisthepathnameofadevicefiletobecreated.
Thesecondargumentmodespecifiestheaccesspermission,fortheowner,groupand
others,alsoS_IFCHRorS_IBLKflagtobeassignedtothefile.
Thethirdargumentdevice_idcontainsthemajorandminordevicenumber.
Example
mknod(“SCSI5”,S_IFBLK | S_IRWXU | S_IRWXG | S_IRWXO,(15<<8) | 3);
Theabovefunctioncreatesablockdevicefile“SCS15”,towhichallthethreei.e.read,write
andexecutepermissionisgrantedforuser,groupandotherswithmajornumberas8and
minornumber3.
On success mknodAPI returns 0 , else it returns -1
118PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
Device file APIs
The following test_mknod.Cprogram illustrates the use of the mknod, open, read, write and
close APIs on a block device file.
#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
intmain(intargc, char* argv[])
{
if(argc!=4)
{
cout<<"usage:"<<argv[0]<<"<file><major_no><minor_no>";
return 0;
}
intmajor=atoi(argv[2];
Intminor=atoi(argv[3]);
(void) mknod(argv[1], S_IFCHR | S_IRWXU | S_IRWXG |
S_IRWXO, (major<<8) | minor);
intrc=1,
Intfd=open(argv[1],O_RDW | O_NONBLOCK | O_NOCTTY);
char buf[256];
while(rc&& fd!=-1)
if((rc=read(fd,buf,sizeof(buf)))<0)
perror("read");
else if(rc)
cout<<buf<<endl;
close(fd);
}
119PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
FIFO file API’s
FIFOfilesaresometimescallednamedpipes.
Pipescanbeusedonlybetweenrelatedprocesseswhenacommonancestorhascreated
thepipe.
CreatingaFIFOissimilartocreatingafile.
IndeedthepathnameforaFIFOexistsinthefilesystem.
The prototype of mkfifois
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
intmkfifo(constchar *path_name, mode_tmode);
The first argument pathname is the pathname(filename) of a FIFO file to be created.
The second argument mode specifies the access permission for user, group and others
and as well as the S_IFIFO flag to indicate that it is a FIFO file.
On success it returns 0 and on failure it returns –1.
120PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
FIFO file API’s
The prototype of pipe is
#include <unistd.h>
intpipe(intfds[2]);
Returns 0 on success and –1 on failure.
If the pipe call executes successfully, the process can read from fd[0] and write to fd[1].
A single process with a pipe is not very useful.
Usually a parent process uses pipes to communicate with its children.
123PROF. SYED MUSTAFA, HKBKCE
UNIT 3 UNIX FILE APIs
The following test_fifo.Cexample illustrates the use of mkfifo, open, read, write
and close APIs for a FIFO file:
#include<iostream.h>
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<string.h>
#include<errno.h>
intmain(intargc,char* argv[])
{
if(argc!=2 && argc!=3)
{
cout<<"usage:"<<argv[0]<<"<file> [<arg>]";
return 0;
}
124PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
INTRODUCTION
A Process is a program under execution in a UNIX or POSIX system.
main FUNCTION
A C program starts execution with a function called main.
The prototype for the main function is
intmain(intargc, char *argv[]);
where argcis the number of command-line arguments, and argvis an array of
pointers to the arguments.
WhenaCprogramisexecutedbythekernelbyoneoftheexecfunctions,a
specialstart-uproutineiscalledbeforethemainfunctioniscalled.
Theexecutableprogramfilespecifiesthisroutineasthestartingaddressforthe
program.
ThisissetupbythelinkeditorwhenitisinvokedbytheCcompiler.
Thisstart-uproutinetakesvaluesfromthekernel,thecommand-linearguments
andtheenvironmentandsetsthingsupsothatthemainfunctioniscalled.
126PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
PROCESS TERMINATION
There are eight ways for a process to terminate.
Normal termination occurs in five ways:
1.Return from main
2.Calling exit
3.Calling _exit or _Exit
4.Return of the last thread from its start routine
5.Calling pthread_exitfrom the last thread
Abnormal termination occurs in three ways:
1.Calling abort
2.Receipt of a signal
3.Response of the last thread to a cancellation request
127PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
Exit Functions
Three functions terminate a program normally:
_exit and _Exit, which return to the kernel immediately, and
exit, which performs certain cleanup processing and then returns to the kernel.
#include <stdlib.h>
void exit(intstatus);
void _Exit(intstatus);
#include <unistd.h>
void _exit(intstatus);
All three exit functions expect a single integer argument, called the exit status.
Returning an integer value from the main function is equivalent to calling exit
with the same value.
Thus exit(0) is the same as return(0) from the main function.
128PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
Exit Functions
Three functions terminate a program normally:
_exit and _Exit, which return to the kernel immediately, and
exit, which performs certain cleanup processing and then returns to the kernel.
#include <stdlib.h>
void exit(intstatus);
void _Exit(intstatus);
#include <unistd.h>
void _exit(intstatus);
All three exit functions expect a single integer argument, called the exit status.
Returning an integer value from the main function is equivalent to calling exit
with the same value.
Thus exit(0) is the same as return(0) from the main function.
129PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
In the following situations the exit status of the process is undefined.
1.any of these functions is called without an exit status.
2.main does a return without a return value.
3.main “falls off the end”, i.eif the exit status of the process is undefined.
intmain()
{
printf(“HKBKCE”);
return(5);
}
$ cc demo.c
$ ./a.out
HKBKCE
$ echo $? //print the exit status
5
130PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
atexitFunction
WithISOC,aprocesscanregisterupto32functionsthatareautomaticallycalledbyexit.
Thesearecalledexithandlersandareregisteredbycallingtheatexitfunction.
#include <stdlib.h>
intatexit(void (*func)(void));
returns: 0 if OK, nonzero on error
This declaration says that we pass the address of a function as the argument to atexit.
When this function is called, it is not passed any arguments and is not expected to
return a value.
The exit function calls these functions in reverse order of their registration.
Each function is called as many times as it was registered.
131PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
Example of exit handlers
static void my_exit1(void);
static void my_exit2(void);
intmain(void)
{
if (atexit(my_exit2) != 0)
perror("can't register my_exit2");
if (atexit(my_exit1) != 0)
perror("can't register my_exit1");
printf("main is done\n");
return(0);
}
static void my_exit1(void)
{
printf("first exit handler\n");
}
static void my_exit2(void)
{
printf("second exit handler\n");
}
Output:
$ ./a.out
main is done
first exit handler
second exit handler
132PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
How a C program is started and the various ways it can terminate
133PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
COMMAND-LINE ARGUMENTS
When a program is executed, the process that does the exec can pass command-line
arguments to the new program.
Example: Echo all command-line arguments to standard output
intmain(intargc, char *argv[])
{
inti;
for (i= 0; i< argc;i++)/* echo all command-line args*/
printf("argv[%d]: %s\n", i, argv[i]);
exit(0);
}
Output:
$ ./echoargarg1 TEST foo
argv[0]: ./echoarg
argv[1]: arg1
argv[2]: TEST
argv[3]: foo
134PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
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
pointer containing 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;
Generally any environmental variable is of the form: name=value.
135PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
MEMORY LAYOUT OF A C PROGRAM
Historically, a C program has been composed of the following pieces:
Textsegment:
ThemachineinstructionsthattheCPUexecutes.
Usually,thetextsegmentissharablesothatonlyasinglecopyneedstobeinmemory
forfrequentlyexecutedprograms,suchastexteditors,theCcompiler,theshells,and
soon.
Also,thetextsegmentisoftenread-only,topreventaprogramfromaccidentally
modifyingitsinstructions.
Initializeddatasegment:
usuallycalledsimplythedatasegment,containingvariablesthatarespecificallyinitialized
intheprogram.
Forexample,theCdeclaration
intmaxcount=99;
appearingoutsideanyfunctioncausesthisvariabletobestoredintheinitializeddata
segmentwithitsinitialvalue.
136PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
MEMORY LAYOUT OF A C PROGRAM
Uninitialized data segment:
Oftencalledthe"bss"segment,namedafteranancientassembleroperatorthatstoodfor
"blockstartedbysymbol."
Datainthissegmentisinitializedbythekerneltoarithmetic0ornullpointersbeforethe
programstartsexecuting.
TheCdeclaration
longsum[1000];
appearingoutsideanyfunctioncausesthisvariabletobestoredintheuninitializeddata
segment.
137PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
MEMORY LAYOUT OF A C PROGRAM
Stack:
whereautomaticvariablesarestored,alongwithinformationthatissavedeachtimea
functioniscalled.
Eachtimeafunctioniscalled,theaddressofwheretoreturntoandcertaininformation
aboutthecaller'senvironment,suchassomeofthemachineregisters,aresavedonthe
stack.
Thenewlycalledfunctionthenallocatesroomonthestackforitsautomaticand
temporaryvariables.
ThisishowrecursivefunctionsinCcanwork.
Eachtimearecursivefunctioncallsitself,anewstackframeisused,soonesetofvariables
doesn'tinterferewiththevariablesfromanotherinstanceofthefunction.
138PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
MEMORY LAYOUT OF A C PROGRAM
Heap:
wheredynamicmemoryallocationusuallytakesplace.
Historically,theheaphasbeenlocatedbetweentheuninitializeddataandthestack.
139PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
MEMORY ALLOCATION
#include <stdlib.h>
void *malloc(size_tsize);
void *calloc(size_tnobj, size_tsize);
void *realloc(void *ptr, size_tnewsize);
On success, it returns: non-null pointer , NULL on Error.
void free(void *ptr);
Thefunctionfreecausesthespacepointedtobyptrtobedeallocated.
Thisfreedspaceisusuallyputintoapoolofavailablememoryandcanbeallocatedinalater
calltooneofthethreeallocfunctions.
.
141PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
MEMORY ALLOCATION
alloca() Function
The function allocahas the same calling sequence as malloc;
however, instead of allocating memory from the heap, the memory is allocated from the
stack frame of the current function.
The advantage is that we don't have to free the space;
it goes away automatically when the function returns.
The allocafunction increases the size of the stack frame.
The disadvantage is that some systems can't support alloca, if it's impossible to increase
the size of the stack frame after the function has been called.
.
142PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
ENVIRONMENT VARIABLES
The environment strings are usually of the form: name=value.
The functions that we can use to set and fetch values from the variables are setenv, putenv,
and getenvfunctions.
The prototype of these functions are:
#include <stdlib.h>
char *getenv(constchar *name);
Returns: pointer to value associated with name, NULL if not found.
Eg:
char *res=getenv(“HOME”);
cout<<“HOME=“<<res<<endl;
output:
HOME=/home/syed
143PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
ENVIRONMENT VARIABLES
intputenv(char *str);
intsetenv(constchar *name, constchar *value, intrewrite);
intunsetenv(constchar *name);
All return: 0 if OK, nonzero on error.
The putenvfunction takes a string of the form name=value and places it in the
environment list.
If name already exists, its old definition is first removed.
144PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
ENVIRONMENT VARIABLES
intsetenv(constchar *name, constchar *value, intrewrite);
All return: 0 if OK, nonzero on error.
The setenvfunction sets name to value.
If name already exists in the environment, then
if rewrite is nonzero, the existing definition for name is first removed;
if rewrite is 0, an existing definition for name is not removed, name is not set to the new
value, and no error occurs.
145PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
ENVIRONMENT VARIABLES
intunsetenv(constchar *name);
All return: 0 if OK, nonzero on error.
The unsetenvfunction removes any definition of name.
It is not an error if such a definition does not exist.
Difference between putenv() and setenv():
Whereas setenv() must allocate memory to create the name=value string from its
arguments,
putenv()is free to place the string passed to it directly into the environment.
146PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
Setjmp() & longjmp() FUNCTIONS
In C, we can't gotoa label that's in another function.
Instead, we must use the setjmpand longjmpfunctions to perform this type of branching.
#include <setjmp.h>
intsetjmp(jmp_bufenv);
Returns: 0 if called directly, nonzero if returning from a call to longjmp
void longjmp(jmp_bufenv, intval);
Thesetjmpfunctionrecordsormarksalocationinaprogramcodesothatlaterwhenthe
longjmpfunctioniscalledfromsomeotherfunction,theexecutioncontinuesfromthe
locationonwards.
Theenvvariable(thefirstargument)recordsthenecessaryinformationneededto
continueexecution.
Theenvisofthejmp_bufdefinedin<setjmp.h>file,itcontainsthetask.
147PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
getrlimit() AND setrlimit() FUNCTIONS
Every process has a set of resource limits, some of which can be queried and changed
by the getrlimitand setrlimitfunctions.
#include <sys/resource.h>
intgetrlimit(intresource, structrlimit*rlptr);
intsetrlimit(intresource, conststructrlimit*rlptr);
Both return: 0 if OK, nonzero on error
Each call to these two functions specifies a single resource and a pointer to the following
structure:
structrlimit
{
rlim_trlim_cur;/* soft limit: current limit */
rlim_trlim_max;/* hard limit: maximum value for rlim_cur*/
};
150PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
getrlimit() AND setrlimit() FUNCTIONS
Three rules govern the changing of the resource limits.
1.A process can change its soft limit to a value less than or equal to its hard limit.
2.A process can lower its hard limit to a value greater than or equal to its soft limit. This
lowering of the hard limit is irreversible for normal users.
3.Only a super user process can raise a hard limit.
An infinite limit is specified by the constant RLIM_INFINITY.
RLIMIT_AS The maximum size in bytes of a process's total availablememory.
RLIMIT_CORE The maximum size in bytes of a core file. A limit of 0 prevents the creation of a corefile.
RLIMIT_CPU
The maximum amount of CPU time in seconds. When the soft limit is exceeded, theSIGXCPU
signal is sent to theprocess.
RLIMIT_DATA
The maximum size in bytes of the data segment: the sum of the initialized data,
uninitialized data, andheap.
RLIMIT_FSIZE
The maximum size in bytes of a file that may be created. When the soft limit is exceeded,
the process is sent the SIGXFSZ signal.
RLIMIT_LOCKS The maximum number of file locks a process canhold.
RLIMIT_NOFILE
The maximum number of open files per process. Changing this limit affects the value
returned bythesysconffunctionforits_SC_OPEN_MAXargument
RLIMIT_NPROC
The maximum number of child processes per real user ID. Changing this limit affects the
value returnedfor_SC_CHILD_MAX bythesysconffunction
151PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
getrlimit() AND setrlimit() FUNCTIONS
Example: Print the current resource limits
#define doit(name) p_limits(#name, name)
intmain(void)
{
#ifdefRLIMIT_AS
doit(RLIMIT_AS);
#endif
doit(RLIMIT_CORE);
doit(RLIMIT_CPU);
doit(RLIMIT_DATA);
doit(RLIMIT_FSIZE);
#ifdefRLIMIT_LOCKS
doit(RLIMIT_LOCKS);
#endif
doit(RLIMIT_NOFILE);
#ifdefRLIMIT_NPROC
doit(RLIMIT_NPROC);
#endif
exit(0);
}
static void pr_limits(char *name, intresource)
{
structrlimitlimit;
if (getrlimit(resource, &limit) < 0)
printf("getrlimiterror for %s", name);
printf("%-14s ", name);
if (limit.rlim_cur== RLIM_INFINITY)
printf("(infinite) ");
else
printf(FMT, limit.rlim_cur);
if (limit.rlim_max== RLIM_INFINITY)
printf("(infinite)");
else
printf(FMT, limit.rlim_max);
}
152PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
UNIX KERNEL SUPPORT FOR PROCESS
UNIXkernelhasaprocesstablethatkeepstrackofallactiveprocesspresentinthe
system.Someoftheseprocessesbelongstothekernelandarecalledas“system
process”.
Everyentryintheprocesstablecontainspointerstothetext,dataandthestack
segmentsandalsotoU-areaofaprocess.
U-areaofaprocessisanextensionoftheprocesstableentryandcontainsotherprocess
specificdatasuchasthefiledescriptortable,currentrootandworkingdirectoryinode
numbersandsetofsystemimposedprocesslimits.
AllprocessesinUNIXsystemexpecttheprocessthatiscreatedbythesystembootcode,
arecreatedbytheforksystemcall.
153PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
UNIX KERNEL SUPPORT FOR PROCESS
154PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
UNIX KERNEL SUPPORT FOR PROCESS
Aftertheforksystemcall,oncethechildprocessiscreated,boththeparentandchild
processesresumesexecution.
Whenaprocessiscreatedbyfork,itcontainsduplicatedcopiesofthetext,dataand
stacksegmentsofitsparentasshownintheFigurebelow.
Alsoithasafiledescriptortable,whichcontainsreferencetothesameopenedfilesas
theparent,suchthattheybothsharethesamefilepointertoeachopenedfiles.
155PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
UNIX KERNEL SUPPORT FOR PROCESS
The process will be assigned with attributes, which are either inherited from its parent or
will be set by the kernel.
Attributes Meaning
real user identification number (rUID) theuserIDofauserwhocreatedtheparentprocess
real group identification number (rGID) thegroupIDofauserwhocreatedthatparentprocess
effective user identification number (eUID)thisallowstheprocesstoaccessandcreatefileswiththe
sameprivilegesastheprogramfileowner.
effective group identification number (eGID)thisallowstheprocesstoaccessandcreatefileswiththe
sameprivilegesasthegrouptowhichtheprogramfile
belongs.
Saved set-UID and saved set-GID thesearetheassignedeUIDandeGIDoftheprocess
respectively
Process group identification number (PGID)
and session identification number (SID)
theseidentifytheprocessgroupandsessionofwhichthe
processismember
Supplementary group identification numbersthisisasetofadditionalgroupIDsforauserwhocreated
theprocess
156PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
UNIX KERNEL SUPPORT FOR PROCESS
The process will be assigned with attributes, which are either inherited from its parent or
will be set by the kernel.
Attributes Meaning
Current directorythisisthereference(inodenumber)toaworkingdirectoryfile
Root directory thisisthereferencetoarootdirectory
Signal handling thesignalhandlingsettings
Signal mask asignalmaskthatspecifieswhichsignalsaretobeblocked
Umask a file mode mask that is used in creation of files to specify which accession rights
should be taken out.
Nice value theprocessschedulingpriorityvalue
Controlling terminalthecontrollingterminaloftheprocess
157PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
UNIX KERNEL SUPPORT FOR PROCESS
In addition to the above attributes, the following attributes are different between the
parent and child processes:
Attributes Meaning
Process identification number (PID)an integer identification number that is unique per process in an
entire operating system.
Parent process identification number
(PPID)
theparentprocessPID
Pending signals thesetofsignalsthatarependingdeliverytotheparentprocess
Alarm clock time theprocessalarmclocktimeisresettozerointhechildprocess
File locks the set of file locks owned by the parent process is not inherited
by the chidprocess
158PROF. SYED MUSTAFA, HKBKCE
UNIT 4 UNIX PROCESSES
UNIX KERNEL SUPPORT FOR PROCESS
fork and exec are commonly used together to spawn a sub-process to execute a different
program.
The advantages of this method are:
A process can create multiple processes to execute multiple programs concurrently.
Because each child process executes in its own virtual address space, the parent process
is not affected by the execution status of its child process.
159PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS IDENTIFIERS
#include <unistd.h>
pid_tgetpid(void);Returns: process ID of calling process
pid_tgetppid(void);Returns: parent process ID of calling process
uid_tgetuid(void);Returns: real user ID of calling process
uid_tgeteuid(void);Returns: effective user ID of calling process
gid_tgetgid(void);Returns: real group ID of calling process
gid_tgetegid(void);Returns: effective group ID of calling process
160PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
fork FUNCTION
An existing process can create a new one by calling the fork function.
#include <unistd.h>
pid_tfork(void);
Returns: 0 in child, process ID of child in parent, 1 on error.
Thenewprocesscreatedbyforkiscalledthechildprocess.
Thisfunctioniscalledoncebutreturnstwice.
Theonlydifferenceinthereturnsisthatthereturnvalueinthechildis0,whereasthe
returnvalueintheparentistheprocessIDofthenewchild.
Thereasonthechild'sprocessIDisreturnedtotheparentisthataprocesscanhave
morethanonechild,andthereisnofunctionthatallowsaprocesstoobtaintheprocess
IDsofitschildren.
161PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
fork FUNCTION
The reason fork returns 0 to the child is that a process can have only a single parent, and
the child can always call getppidto obtain the process ID of its parent.
(Process ID 0 is reserved for use by the kernel, so it's not possible for 0 to be the process
ID of a child.)
Both the child and the parent continue executing with the instruction that follows the
call to fork.
The child is a copy of the parent.
For example, the child gets a copy of the parent's data space, heap, and stack.
Note that this is a copy for the child;
the parent and the child do not share these portions of memory.
The parent and the child share the text segment .
162PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
fork FUNCTION
Example programs:
Program 1
/* Program to demonstrate fork function Program name –fork1.c */
#include<unistd.h>
void main( )
{
fork( );
printf(“\n hello USP”);
}
Output :
$ cc fork1.c
$ ./a.out
hello USP
hello USP
Note : The statement hello USP is executed twice as both the child and parent have executed that instruction.
163PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
fork FUNCTION
Example programs:
Program 2/* Program name –fork2.c */
#include<unistd.h>
void main( )
{
printf(“\n 6 sem“);
fork( );
printf(“\n hello USP”);
}
Output :
$ cc fork2.c
$ ./a.out
6 sem
hello USP
hello USP
Note: The statement 6 semis executed only once by the parent because it is called before fork and statement hello USP is
executed twice by child and parent.
164PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
fork FUNCTION
The two main reasons for fork to fail are
1.iftoomanyprocessesarealreadyinthesystem,whichusuallymeansthatsomething
elseiswrong,or
2.ifthetotalnumberofprocessesforthisrealuserIDexceedsthesystem'slimit.
Therearetwousesforfork:
1.Whenaprocesswantstoduplicateitselfsothattheparentandchildcaneachexecute
differentsectionsofcodeatthesametime.Thisiscommonfornetworkservers,the
parentwaitsforaservicerequestfromaclient.Whentherequestarrives,theparent
callsforkandletsthechildhandletherequest.Theparentgoesbacktowaitingforthe
nextservicerequesttoarrive.
2.Whenaprocesswantstoexecuteadifferentprogram.Thisiscommonforshells.Inthis
case,thechilddoesanexecrightafteritreturnsfromthefork.
165PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
vforkFUNCTION
Thefunctionvforkhasthesamecallingsequenceandsamereturnvaluesasfork.
Thevforkfunctionisintendedtocreateanewprocesswhenthepurposeofthenew
processistoexecanewprogram.
Thevforkfunctioncreatesthenewprocess,justlikefork,withoutcopyingtheaddress
spaceoftheparentintothechild,asthechildwon'treferencethataddressspace;the
childsimplycallsexec(orexit)rightafterthevfork.
Instead,whilethechildisrunninganduntilitcallseitherexecorexit,thechildrunsin
theaddressspaceoftheparent.
Thisoptimizationprovidesanefficiencygainonsomepagedvirtual-memory
implementationsoftheUNIXSystem.
Anotherdifferencebetweenthetwofunctionsisthatvforkguaranteesthatthechild
runsfirst,untilthechildcallsexecorexit.Whenthechildcallseitherofthesefunctions,
theparentresumes.
166PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
vforkFUNCTION
Example of vforkfunction
intglob = 6;/* external variable in initialized data */
intmain(void)
{
intvar=88; /* automatic variable on the stack */
pid_tpid;
printf("before vfork\n");
if ((pid= vfork()) < 0)
perror("vforkerror");
else if (pid== 0) /* child */
{
glob++; /* modify parent's variables */
var++;
_exit(0); /* child terminates */
}
/* Parent continues here.*/
printf("pid= %d\n", getpid());
printf("glob = %d, var= %d\n", glob, var);
exit(0);
}
Output:
$ ./a.out
before vfork
pid= 29039
glob = 7, var= 89
167PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
Wait() AND waitpid() FUNCTIONS
Whenaprocessterminates,eithernormallyorabnormally,thekernelnotifiestheparent
bysendingtheSIGCHLDsignaltotheparent.
Becausetheterminationofachildisanasynchronousevent-itcanhappenatanytime
whiletheparentisrunning-thissignalistheasynchronousnotificationfromthekernel
totheparent.
Theparentcanchoosetoignorethissignal,oritcanprovideafunctionthatiscalled
whenthesignaloccurs:asignalhandler.
Aprocessthatcallswait()orwaitpid()can:
1.Block,ifallofitschildrenarestillrunning
2.Returnimmediatelywiththeterminationstatusofachild,ifachildhasterminatedand
iswaitingforitsterminationstatustobefetched
3.Returnimmediatelywithanerror,ifitdoesn'thaveanychildprocesses.
168PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
Wait() AND waitpid() FUNCTIONS
#include <sys/wait.h>
pid_twait(int*statloc);
pid_twaitpid(pid_tpid, int*statloc, intoptions);
1.Both return: process ID if OK, 0 (see later), or 1 on error.
2.The argument statlocis a pointer to an integer.
3.If this argument is not a null pointer, the termination status of the terminated process is
stored in the location pointed to by the argument
169PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
Wait() AND waitpid() FUNCTIONS
Thedifferencesbetweenthesetwofunctionsareasfollows.
1.Thewaitfunctioncanblockthecalleruntilachildprocessterminates,whereas
waitpid()hasanoptionthatpreventsitfromblocking.
2.Thewaitpid()functiondoesn'twaitforthechildthatterminatesfirst;
3.Ithasanumberofoptionsthatcontrolwhichprocessitwaitsfor.
4.Ifachildhasalreadyterminatedandisazombie,waitreturnsimmediatelywiththat
child'sstatus.Otherwise,itblocksthecalleruntilachildterminates.
5.Ifthecallerblocksandhasmultiplechildren,waitreturnswhenoneterminates.
170PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
Wait() AND waitpid() FUNCTIONS
The interpretation of the pidargument for waitpid() depends on its value:
PidValue Action
pid== 1 Waits for any child process. In this respect, waitpidis equivalent
to wait
pid> 0 Waits for the child whose process ID equals pid
pid== 0 Waits for any child whose process group ID equals that of the
calling process.
pid< 1 Waits for any child whose process group ID equals the absolute
value of pid.
171PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
Wait() AND waitpid() FUNCTIONS
Macros to examine the termination status returned by wait() and waitpid():
Macro Description
WIFEXITED(status)True if status was returned for a child that terminated normally.
In this case, we can execute
WEXITSTATUS (status)
to fetch the low-order 8 bits of the argument that the child passed to
exit, _exit,or_Exit.
WIFSIGNALED (status)True if status was returned for a child that terminated abnormally, by
receipt of a signal that it didn't catch. In this case, we can execute
WTERMSIG (status)
to fetch the signal number that caused the termination.
Additionally, some implementations (but not the Single UNIX
Specification) define the macro
WCOREDUMP (status)
that returns true if a core file of the terminated process was generated.
172PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
Wait() AND waitpid() FUNCTIONS
Macros to examine the termination status returned by wait() and waitpid():
Macro Description
WIFSTOPPED (status)True if status was returned for a child that is currently
stopped. In this case, we can execute
WSTOPSIG (status)
to fetch the signal number that caused the child to stop.
WIFCONTINUED (status)True if status was returned for a child that has been
continued after a job control stop
173PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
Wait() AND waitpid() FUNCTIONS
pid_twaitpid(pid_tpid, int*statloc, intoptions);
The options constants for waitpid()
Constant Description
WCONTINUED Iftheimplementationsupportsjobcontrol,thestatusofanychildspecifiedbypidthat
hasbeencontinuedafterbeingstopped,butwhosestatushasnotyetbeenreported,
isreturned.
WNOHANG Thewaitpid()functionwillnotblockifachildspecifiedbypidisnotimmediately
available.Inthiscase,thereturnvalueis0.
WUNTRACED Iftheimplementationsupportsjobcontrol,thestatusofanychildspecifiedbypidthat
hasstopped,andwhosestatushasnotbeenreportedsinceithasstopped,is
returned.
TheWIFSTOPPEDmacrodetermineswhetherthereturnvaluecorrespondstoa
stoppedchildprocess.
174PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
Wait() AND waitpid() FUNCTIONS
pid_twaitpid(pid_tpid, int*statloc, intoptions);
Thewaitpidfunctionprovidesthreefeaturesthataren'tprovidedbythewaitfunction.
1.Thewaitpid()functionletsuswaitforoneparticularprocess,whereasthewait()
functionreturnsthestatusofanyterminatedchild.
2.Thewaitpid()functionprovidesanonblockingversionofwait.Therearetimeswhen
wewanttofetchachild'sstatus,butwedon'twanttoblock.
3.Thewaitpid()functionprovidessupportforjobcontrolwiththeWUNTRACEDand
WCONTINUEDoptions.
175PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
Wait() AND waitpid() FUNCTIONS
Program to Demonstrate various exit statuses
#include <sys/wait.h>
void pr_exit(intstatus)
{
if (WIFEXITED(status))
printf("normal termination, exit status = %d\n", WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("abnormal termination, signal number = %d\n", WTERMSIG(status));
else if (WIFSTOPPED(status))
printf("child stopped, signal number = %d\n", WSTOPSIG(status));
}
176PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
Wait() AND waitpid() FUNCTIONS
Program to Demonstrate various exit statuses
intmain(void)
{
pid_tpid; intstatus;
if ((pid= fork()) < 0)
perror("fork error");
else if (pid== 0)/* child */
exit(7);
if (wait(&status) != pid)/* wait for child */
perror("wait error");
pr_exit(status);/* and print its status */
if ((pid= fork()) < 0)
perror("fork error");
else if (pid== 0)/* child */
abort(); /* generates SIGABRT */
if (wait(&status) != pid)/* wait for child */
perror("wait error");
pr_exit(status);/* and print its status */
if ((pid= fork()) < 0)
perror("fork error");
else if (pid== 0)/* child */
status /= 0;/* divide by 0 generates SIGFPE */
if (wait(&status) != pid)/* wait for child */
perror("wait error");
pr_exit(status);/* and print its status */
exit(0);
}
177PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
Wait3() AND wait4() FUNCTIONS
Theonlyfeatureprovidedbythesetwofunctionsthatisn'tprovidedbythewait,waitid,
andwaitpidfunctionsisanadditionalargumentthatallowsthekerneltoreturna
summaryoftheresourcesusedbytheterminatedprocessandallitschildprocesses.
The prototypes of these functions are:
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
pid_twait3(int*statloc, intoptions, structrusage*rusage);
pid_twait4(pid_tpid, int*statloc, intoptions, structrusage*rusage);
Both return: process ID if OK,-1 on error.
TheresourceinformationincludessuchstatisticsastheamountofuserCPUtime,the
amountofsystemCPUtime,numberofpagefaults,numberofsignalsreceivedetc.the
resourceinformationisavailableonlyforterminatedchildprocessnotfortheprocess
thatwerestoppedduetojobcontrol.
178PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
RACE CONDITIONS
Araceconditionoccurswhenmultipleprocessesaretryingtodosomethingwithshared
dataandthefinaloutcomedependsontheorderinwhichtheprocessesrun.
Example:Theprogrambelowoutputstwostrings:onefromthechildandonefromtheparent.The
programcontainsaraceconditionbecausetheoutputdependsontheorderinwhichtheprocessesarerun
bythekernelandforhowlongeachprocessruns.
static void charatatime(char *);
intmain(void)
{
pid_tpid;
if ((pid= fork()) < 0)
peror("fork error");
else if (pid== 0)
charatatime("output from child\n");
else
charatatime("output from parent\n");
exit(0);
}
static void charatatime(char *str)
{
char*ptr;
intc;
setbuf(stdout, NULL); /* set unbuffered */
for (ptr= str; (c = *ptr++) != 0; )
putc(c, stdout);
}
Output:
$ ./a.out
ooutputfrom child
utputfrom parent
179PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
RACE CONDITIONS
Howtoavoidracecondition?
static void charatatime(char *);
intmain(void)
{
pid_tpid;
TELL_WAIT();
if ((pid= fork()) < 0)
peror("fork error");
else if (pid== 0)
{
WAIT_PARENT();/* parent goes first */
charatatime("output from child\n");
}
else
{
charatatime("output from parent\n");
TELL_CHILD(pid);
}
exit(0);
}
static void charatatime(char *str)
{
char*ptr;
intc;
setbuf(stdout, NULL); /* set unbuffered */
for (ptr= str; (c = *ptr++) != 0; )
putc(c, stdout);
}
Output:
$ ./a.out
output from parent
output from child
180PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
RACE CONDITIONS
Howtoavoidracecondition?
static void charatatime(char *);
intmain(void)
{
pid_tpid;
TELL_WAIT();
if ((pid= fork()) < 0)
peror("fork error");
else if (pid== 0)
{
charatatime("output from child\n");
TELL_PARENT(getppid());
}
else
{
WAIT_CHILD();/* child goes first */
charatatime("output from parent\n");
}
exit(0);
}
static void charatatime(char *str)
{
char*ptr;
intc;
setbuf(stdout, NULL); /* set unbuffered */
for (ptr= str; (c = *ptr++) != 0; )
putc(c, stdout);
}
Output:
$ ./a.out
output from child
output from parent
181PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROLexec() Functions
Whenaprocesscallsoneoftheexecfunctions,thatprocessiscompletelyreplacedby
thenewprogram,andthenewprogramstartsexecutingatitsmainfunction.
TheprocessIDdoesnotchangeacrossanexec,becauseanewprocessisnotcreated;
execmerelyreplacesthecurrentprocess-itstext,data,heap,andstacksegments-
withabrandnewprogramfromdisk.
Thereare6execfunctions:
182PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
exec() Functions
Relationship of the six execfunctions
InmanyUNIXsystemimplementations,onlyoneofthesesixfunctions,
execve,isasystemcallwithinthekernel.
Theotherfivearejustlibraryfunctionsthateventuallyinvokethissystemcall.
184PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
exec() Functions
char *env_init[] = { "USER=syed", "PATH=/tmp",
NULL };
intmain(void)
{
pid_tpid;
if ((pid= fork()) < 0)
perror("fork error");
else if (pid== 0)
{ /* specify pathname, specify environment */
if (execle("/home/sar/bin/echoall", "echoall",
"myarg1",
"MY ARG2", (char *)0, env_init) < 0)
perror("execleerror");
}
if (waitpid(pid, NULL, 0) < 0)
perror("wait error")
if ((pid= fork()) < 0)
perror("fork error");
else if (pid== 0)
{/* specify filename, inherit environment */
if (execlp("echoall", "echoall", "only 1 arg",
(char *)0) < 0)
perror("execlperror");
}
exit(0);
}
Output:
$ ./a.out
argv[0]: echoall
argv[1]: myarg1
argv[2]: MY ARG2
PATH=/tmp
$ argv[0]: echoall
argv[1]: only 1 arg
USER=syed
LOGNAME=syed
SHELL=/bin/bash
HOME=/home/sar
185PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
exec() Functions
echoall.c
intmain(intargc, char *argv[])
{
inti;
char **ptr;
extern char **environ;
for (i= 0; i< argc; i++) /* echo all command-line args*/
printf("argv[%d]: %s\n", i, argv[i]);
for (ptr= environ; *ptr!= 0; ptr++) /* and all envstrings */
printf("%s\n", *ptr);
exit(0);
}
186PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
CHANGING USER IDs AND GROUP IDs
Whenourprogramsneedadditionalprivilegesorneedtogainaccesstoresourcesthat
theycurrentlyaren'tallowedtoaccess,theyneedtochangetheiruserorgroupIDtoan
IDthathastheappropriateprivilegeoraccess.
Similarly,whenourprogramsneedtolowertheirprivilegesorpreventaccesstocertain
resources,theydosobychangingeithertheiruserIDorgroupIDtoanIDwithoutthe
privilegeorabilityaccesstotheresource.
We can set the real user ID and effective user ID with the setuidfunction. Similarly, we can
set the real group ID and the effective group ID with the setgidfunction.
#include <unistd.h>
intsetuid(uid_tuid);
intsetgid(gid_tgid);
Both return: 0 if OK, -1 on error
187PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
CHANGING USER IDs AND GROUP IDs
TherearerulesforwhocanchangetheIDs.
Let'sconsideronlytheuserIDfornow.(EverythingwedescribefortheuserIDalsoapplies
tothegroupID.)
1.Iftheprocesshassuperuserprivileges,thesetuidfunctionsetstherealuserID,effective
userID,andsavedset-user-IDtouid.
2.Iftheprocessdoesnothavesuperuserprivileges,butuidequalseithertherealuserIDor
thesavedsetuserID,setuidsetsonlytheeffectiveuserIDtouid.TherealuserIDandthe
savedset-user-IDarenotchanged.
3.Ifneitherofthesetwoconditionsistrue,errnoissettoEPERM,and–1isreturned.
188PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
CHANGING USER IDs AND GROUP IDs
setreuid() and setregid() Functions
Historically, BSD supported the swapping of the real user ID and the effective
user ID with the setreuid() function.
#include <unistd.h>
int setreuid(uid_t ruid, uid_t euid);
intsetregid(gid_trgid, gid_tegid);
Both return: 0 if OK, –1 on error
189PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
CHANGING USER IDs AND GROUP IDs
Seteuid() and setegid() Functions
POSIX.1 includes the two functions seteuidand setegid.
These functions are similar to setuidand setgid, but only the effective user ID
or effective group ID is changed.
#include <unistd.h>
intseteuid(uid_tuid);
intsetegid(gid_tgid);
Both return: 0 if OK, –1 on error
190PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
Interpreter Files
All contemporary UNIX systems support interpreter files.
These files are text files that begin with a line of the form
#! pathname [ optional-argument ]
The space between the exclamation point and the pathname is optional.
The most common of these interpreter files begin with the line
#!/bin/sh
#!/usr/bin/perl
The pathname is normally an absolute pathname, since no special operations
are performed on it
191PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
Interpreter Files
Using the -f option with an interpreter file lets us write
#!/bin/awk-f
(awkprogram follows in the interpreter file)
Eg:
#!/bin/awk-f
BEGIN {
for (i = 0; i < ARGC; i++)
printf "ARGV[%d] = %s\n", i, ARGV[i]
exit
}
192PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
system() Function
It is convenient to execute a command string from within a program.
Eg:
system("date > file");
#include <stdlib.h>
intsystem(constchar *cmdstring);
If cmdstringis a null pointer, system returns nonzero only if a command
processor is available.
193PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
The system function, without signal handling
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
intsystem(constchar *cmdstring) /* version without signal handling */
{
pid_tpid;
intstatus;
if (cmdstring== NULL)
return(1); /* always a command processor with UNIX */
if ((pid= fork()) < 0)
status = -1; /* probably out of processes */
194PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
else if (pid== 0)
{ /* child */
execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
_exit(127); /* execlerror */
}
else
while (waitpid(pid, &status, 0) < 0) /* parent */
if (errno!= EINTR)
{
status = -1; /* error other than EINTR from waitpid() */
break;
}
return(status);
}
195PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS ACCOUNTING
MostUNIXsystemsprovideanoptiontodoprocessaccounting.
Whenenabled,thekernelwritesanaccountingrecordeachtimeaprocess
terminates.
Theseaccountingrecordsaretypicallyasmallamountofbinarydatawith
thenameofthecommand,theamountofCPUtimeused,theuserIDand
groupID,thestartingtime,andsoon.
Asuperuserexecutesactionwithapathnameargumenttoenable
accounting.
Theaccountingrecordsarewrittentothespecifiedfile,whichisusually
/var/account/acct.Accountingisturnedoffbyexecutingacctonwithoutany
arguments.
196PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS ACCOUNTING
The data required for the accounting record, such as CPU times and number
of characters transferred, is kept by the kernel in the process table and
initialized whenever a new process is created, as in the child after a fork.
Each accounting record is written when the process terminates.
This means that the order of the records in the accounting file corresponds
to the termination order of the processes, not the order in which they were
started.
The accounting records correspond to processes, not programs.
A new record is initialized by the kernel for the child after a fork, not when a
new program is executed.
197PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS ACCOUNTING
The structure of the accounting records is defined in the header <sys/acct.h>
and looks something like
typedefu_shortcomp_t;/* 3-bit base 8 exponent; 13-bit fraction */
198PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
USER IDENTIFICATION
AnyprocesscanfindoutitsrealandeffectiveuserIDandgroupID.
wewanttofindouttheloginnameoftheuserwho'srunningthe
program.
Wecouldcallgetpwuid(getuid()),butwhatifasingleuserhasmultiple
loginnames,eachwiththesameuserID?(Apersonmighthavemultiple
entriesinthepasswordfilewiththesameuserIDtohaveadifferentlogin
shellforeachentry.)
Thesystemnormallykeepstrackofthenameweloginandthegetlogin
functionprovidesawaytofetchthatloginname.
199PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
USER IDENTIFICATION
#include <unistd.h>
char *getlogin(void);
Returns : pointer to string giving login name if OK, NULL on error
This function can fail if the process is not attached to a terminal that a user
logged in to.
200PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS TIMES
We describe three times that we can measure: wall clock time, user CPU time,
and system CPU time.
Any process can call the times function to obtain these values for itself and
any terminated children.
#include <sys/times.h>
clock_ttimes(structtms*buf);
Returns: elapsed wall clock time in clock ticks if OK, 1 on error
201PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS TIMES
This function fills in the tmsstructure pointed to by buf:
structtms
{
clock_ttms_utime;/* user CPU time */
clock_ttms_stime;/* system CPU time */
clock_ttms_cutime; /* user CPU time, terminated children */
clock_ttms_cstime; /* system CPU time, terminated children */
};
Note that the structure does not contain any measurement for the wall clock time.
Instead, the function returns the wall clock time as the value of the function, each time
it's called.
This value is measured from some arbitrary point in the past, so we can't use its absolute
value; instead, we use its relative value.
202PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
TERMINAL LOGINS
Theterminalswereeitherlocal(directlyconnected)orremote(connected
throughamodem).
Ineithercase,theseloginscamethroughaterminaldevicedriverinthe
kernel.
Thesystemadministratorcreatesafile,usually/etc/ttys,thathasoneline
perterminaldevice.
Eachlinespecifiesthenameofthedeviceandotherparametersthatare
passedtothegetty().
203PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
TERMINAL LOGINS
One parameter is the baud rate of the terminal, for example.
When the system is bootstrapped, the kernel creates process ID 1, the init
process, and it is initthat brings the system up multiuser.
The initprocess reads the file /etc/ttysand, for every terminal device that
allows a login, does a fork followed by an exec of the program getty().
204PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
TERMINAL LOGINS
Processes invoked by initto allow terminal logins
205PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
TERMINAL LOGINS
AlltheprocessesshowninthediagramhavearealuserIDof0andan
effectiveuserIDof0(i.e.,theyallhavesuperuserprivileges).
Theinitprocessalsoexecsthegetty()programwithanemptyenvironment.
Itisgetty()thatcallsopenfortheterminaldevice.
Theterminalisopenedforreadingandwriting.
Ifthedeviceisamodem,theopenmaydelayinsidethedevicedriveruntilthe
modemisdialedandthecallisanswered.
Oncethedeviceisopen,filedescriptors0,1,and2aresettothedevice.
206PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
TERMINAL LOGINS
Thengetty()outputssomethinglikeloginandwaitsforustoenterouruser
name.
When we enter our user name, getty'sjob is complete, and it then invokes the
login program, similar to
execle("/bin/login", "login", "-p", username, (char *)0, envp);
207PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
TERMINAL LOGINS
State of processes after loginhas been invoked
208PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
TERMINAL LOGINS
Alltheprocessesshowninthediagramhavesuperuserprivileges,since
theoriginalinitprocesshassuperuserprivileges.
Ifwelogincorrectly,loginwill
Changetoourhomedirectory(chdir)
Changetheownershipofourterminaldevice(chown)soweownit
Changetheaccesspermissionsforourterminaldevicesowehavepermissionto
readfromandwritetoit
SetourgroupIDsbycallingsetgidandinitgroups
209PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
TERMINAL LOGINS
Initializetheenvironmentwithalltheinformationthatloginhas:ourhome
directory(HOME),shell(SHELL),username(USERandLOGNAME),andadefault
path(PATH)
ChangetoouruserID(setuid)andinvokeourloginshell,asin
execl("/bin/sh","-sh",(char*)0);
Theminussignasthefirstcharacterofargv[0]isaflagtoalltheshells
thattheyarebeinginvokedasaloginshell.
Theshellscanlookatthischaracterandmodifytheirstart-up
accordingly.
210PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
TERMINAL LOGINS
Arrangement of processes after everything is set for a terminal login
211PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
NETWORK LOGINS
Themain(physical)differencebetweenloggingintoasystemthrougha
serialterminalandloggingintoasystemthroughanetworkisthatthe
connectionbetweentheterminalandthecomputerisn'tpoint-to-point.
Withtheterminallogins,initknowswhichterminaldevicesareenabledfor
loginsandspawnsagettyprocessforeachdevice.
Inthecaseofnetworklogins,however,alltheloginscomethroughthe
kernel'snetworkinterfacedrivers(e.g.,theEthernetdriver).
212PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
NETWORK LOGINS
LetaTCPconnectionrequestarrivesfortheTELNETserver.
TELNETisaremoteloginapplicationthatusestheTCPprotocol.
Auseronanotherhost(thatisconnectedtotheserver'shostthrougha
networkofsomeform)oronthesamehostinitiatestheloginbystarting
theTELNETclient:
telnethostname
TheclientopensaTCPconnectiontohostname,andtheprogramthat's
startedonhostnameiscalledtheTELNETserver.
TheclientandtheserverthenexchangedataacrosstheTCPconnection
usingtheTELNETapplicationprotocol.
213PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
NETWORK LOGINS
Figure shows the sequence of processes involved in executing the TELNET
server, called telnetd.
Sequence of processes involved in executing TELNETserver
214PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
NETWORK LOGINS
Thetelnetdprocessthenopensapseudo-terminaldeviceandsplitsinto
twoprocessesusingfork.
Theparenthandlesthecommunicationacrossthenetworkconnection,and
thechilddoesanexecoftheloginprogram.
Theparentandthechildareconnectedthroughthepseudoterminal.
Beforedoingtheexec,thechildsetsupfiledescriptors0,1,and2tothe
pseudoterminal.
Ifwelogincorrectly,loginperformsthesamestepsasdescribedearlier.
ItchangestoourhomedirectoryandsetsourgroupIDs,userID,andour
initialenvironment.
Thenloginreplacesitselfwithourloginshellbycallingexec.
215PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
NETWORK LOGINS
Arrangementofprocessesaftereverythingissetforanetworklogin
216PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
NETWORK LOGINS
Arrangementofprocessesaftereverythingissetforanetworklogin
217PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
PROCESS GROUPS
Aprocessgroupisacollectionofoneormoreprocesses,usuallyassociated
withthesamejob,thatcanreceivesignalsfromthesameterminal.
EachprocessgrouphasauniqueprocessgroupID.
ProcessgroupIDsaresimilartoprocessIDs:theyarepositiveintegersand
canbestoredinapid_tdatatype.
Thefunctiongetpgrp()returnstheprocessgroupIDofthecallingprocess.
#include <unistd.h>
pid_tgetpgrp(void);
Returns:processgroupIDofcallingprocess
218PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
PROCESS GROUPS
Eachprocessgroupcanhaveaprocessgroupleader.
TheleaderisidentifiedbyitsprocessgroupIDbeingequaltoitsprocessID.
Itispossibleforaprocessgroupleadertocreateaprocessgroup,create
processesinthegroup,andthenterminate.
Theprocessgroupstillexists,aslongasatleastoneprocessisinthegroup,
regardlessofwhetherthegroupleaderterminates.
Thisiscalledtheprocessgrouplifetime-theperiodoftimethatbeginswhen
thegroupiscreatedandendswhenthelastremainingprocessleavesthe
group.
Thelastremainingprocessintheprocessgroupcaneitherterminateor
entersomeotherprocessgroup.
219PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
PROCESS GROUPS
A process joins an existing process group or creates a new process group by
calling setpgid().
#include <unistd.h>
intsetpgid(pid_tpid, pid_tpgid);
Returns: 0 if OK, -1 on error
This function sets the process group ID to pgidin the process whose process
ID equals pid.
If the two arguments are equal, the process specified by pidbecomes a
process group leader.
If pidis 0, the process ID of the caller is used.
220PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
SESSIONS
A session is a collection of one or more process groups.
For example, we could have the arrangement shown in the diagram below.
Here we have three process groups in a single session.
Arrangement of processes into process groups andsessions
221PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
SESSIONS
A process establishes a new session by calling the setsid() function.
#include <unistd.h>
pid_tsetsid(void);
Returns: process group ID if OK, -1 on error
If the calling process is not a process group leader, this function creates a new
session.
Three things may happen.
1.The process becomes the session leader of this new session. (A session
leader is the process that creates a session.) The process is the only process
in this new session.
2.The process becomes the process group leader of a new process group.
3.The new process group ID is the process ID of the calling process.
222PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
SESSIONS
setsid() function returns an error if the caller is already a process group leader.
The getsidfunction returns the process group ID of a process's session leader.
#include <unistd.h>
pid_tgetsid(pid_tpid);
Returns: session leader's process group ID if OK, -1 on error
If pidis 0, getsidreturns the process group ID of the calling process's session
leader.
223PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
CONTROLLING TERMINAL
Sessions and process groups have a few other characteristics.
1.Asessioncanhaveasinglecontrollingterminal.Thisisusuallytheterminal
device(inthecaseofaterminallogin)orpseudo-terminaldevice(inthe
caseofanetworklogin)onwhichwelogin.
2.Thesessionleaderthatestablishestheconnectiontothecontrolling
terminaliscalledthecontrollingprocess.
3.Theprocessgroupswithinasessioncanbedividedintoasingleforeground
processgroupandoneormorebackgroundprocessgroups.
4.Ifasessionhasacontrollingterminal,ithasasingleforegroundprocess
group,andallotherprocessgroupsinthesessionarebackgroundprocess
groups.
224PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
CONTROLLING TERMINAL
5.Wheneverwetypetheterminal'sinterruptkey(oftenDELETEorControl-C),
thiscausestheinterruptsignalbesenttoallprocessesintheforeground
processgroup.
6.Wheneverwetypetheterminal'squitkey(oftenControl-\),thiscausesthe
quitsignaltobesenttoallprocessesintheforegroundprocessgroup.
7.Ifamodem(ornetwork)disconnectisdetectedbytheterminalinterface,
thehang-upsignalissenttothecontrollingprocess(thesessionleader).
225PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
CONTROLLING TERMINAL
Process groups and sessions showing controllingterminal
226PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
tcgetpgrp(), tcsetpgrp() & tcgetsid()
Weneedawaytotellthekernelwhichprocessgroupistheforeground
processgroup,sothattheterminaldevicedriverknowswheretosendthe
terminalinputandtheterminal-generatedsignals.
Toretrievetheforegroundprocessgroup-idandtosettheforeground
processgroup-idwecanusetcgetprgp()andtcsetpgrp()function.
The prototype of these functions are :
#include <unistd.h>
pid_ttcgetpgrp(intfiledes);
Returns : process group ID of foreground process group if OK, -1 on error.
227PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
tcgetpgrp(), tcsetpgrp() & tcgetsid()
Thefunctiontcgetpgrp()returnstheprocessgroupIDoftheforeground
processgroupassociatedwiththeterminalopenonfiledesc.
Iftheprocesshasacontrollingterminal,theprocesscancalltcsetpgrpto
settheforegroundprocessgroupIDtopgrpid.
ThevalueofpgrpidmustbetheprocessgroupIDofaprocessgroupinthe
samesession,andfiledesmustrefertothecontrollingterminalofthe
session.
228PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
tcgetpgrp(), tcsetpgrp() & tcgetsid()
The single UNIX specification defines an XSI extension called tcgetsid() to allow
an application to obtain the process group-ID for the session leader given a file
descriptor for the controlling terminal.
#include <termios.h>
pid_ttcgetsid(intfiledesc);
Returns: session leader’s process group ID if Ok, -1 on error
229PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
JOB CONTROL
Thisfeatureallowsustostartmultiplejobs(groupsofprocesses)fromasingle
terminalandtocontrolwhichjobscanaccesstheterminalandwhichjobsare
toruninthebackground.
Jobcontrolrequiresthreeformsofsupport:
1.A shell that supports job control
2.The terminal driver in the kernel must support job control
3.The kernel must support certain job-control signals
230PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
JOB CONTROL
Using job control from a shell, we can start a job in either the foreground or
the background.
A job is simply a collection of processes, often a pipeline of processes.
For example,
$vi main.c
starts a job consisting of one process in the foreground.
The commands
$pr*.c | lpr& , $make all & , $start
start two jobs in the background.
All the processes invoked by these background jobs are in the background.
231PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
JOB CONTROL
Theinteractionwiththeterminaldriverarisesbecauseaspecialterminal
characteraffectstheforegroundjob:thesuspendkey(typicallyControl-Z).
EnteringthischaractercausestheterminaldrivertosendtheSIGTSTPsignal
toallprocessesintheforegroundprocessgroup.
Thejobsinanybackgroundprocessgroupsaren'taffected.
Theterminaldriverlooksforthreespecialcharacters,whichgenerate
signalstotheforegroundprocessgroup.
1.The interrupt character (typically DELETE or Control-C) generates SIGINT.
2.The quit character (typically Control-\(back slash)) generates SIGQUIT.
3.The suspend character (typically Control-Z) generates SIGTSTP.
232PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
JOB CONTROL
Thissignalnormallystopsthebackgroundjob;byusingtheshell,weare
notifiedofthisandcanbringthejobintotheforegroundsothatitcanread
fromtheterminal.
The following demonstrates this:
233PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
JOB CONTROL
The shell starts the cat process in the background, but when cat tries to read
its standard input (the controlling terminal), the terminal driver, knowing that it
is a background job, sends the SIGTTIN signal to the background job.
234PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
JOB CONTROL
235PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
SHELL EXECUTION OF PROGRAMS
236PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
SHELL EXECUTION OF PROGRAMS
237PROF. SYED MUSTAFA, HKBKCE
UNIT 5 PROCESS CONTROL
PROCESS RELATIONSHIP
ORPHANED PROCESS GROUPS
A process whose parent terminates is called an orphan and is inherited by the
initprocess. A process that forks a child and then terminates.
238PROF. SYED MUSTAFA, HKBKCE
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
Signals are software interrupts.
Signals provide a way of handling asynchronous events: a user at a terminal
typing the interrupt key to stop a program or the next program in a pipeline
terminating prematurely.
When a signal is sent to a process, it is pending on the process to handle it.
The process can react to pending signals in one of three ways:
1.Acceptthedefaultactionofthesignal,whichformostsignalswillterminatethe
process.
2.Ignorethesignal.Thesignalwillbediscardedandithasnoaffectwhatsoeveronthe
recipientprocess.
3.Invokeauser-definedfunction.Thefunctionisknownasasignalhandlerroutine
andthesignalissaidtobecaughtwhenthisfunctioniscalled.
239PROF. SYED MUSTAFA, HKBKCE
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
240PROF. SYED MUSTAFA, HKBKCE
Name Description Defaultaction
SIGABRT abnormal termination(abort)terminate+core
SIGALRM timer expired(alarm) terminate
SIGCHLD change in status ofchild ignore
SIGCONT continue stoppedprocess continue/ignore
SIGFPE arithmeticexception terminate+core
SIGINT terminal interruptcharacterterminate
SIGIO asynchronousI/O terminate/ignore
SIGKILL termination terminate
SIGPIPE write to pipe with noreadersterminate
SIGQUIT terminal quitcharacter terminate+core
SIGSEGV invalid memoryreference terminate+core
SIGSTOP stop stopprocess
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
241PROF. SYED MUSTAFA, HKBKCE
Name Description Defaultaction
SIGTTOU background write to control tty stop process
SIGUSR1 user-defined signal Terminate
SIGUSR2 user-defined signal Terminate
SIGTERM termination Terminate
SIGTSTP terminal stop character stop process
SIGTTIN background read from control tty stop process
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
242PROF. SYED MUSTAFA, HKBKCE
THE UNIX KERNEL SUPPORT OFSIGNALS
Whenasignalisgeneratedforaprocess,thekernelwillsetthecorresponding
signalflagintheprocesstableslotoftherecipientprocess.
Iftherecipientprocessisasleep,thekernelwillawakentheprocessbyschedulingit.
Whentherecipientprocessruns,thekernelwillchecktheprocessU-areathat
containsanarrayofsignalhandlingspecifications.
Ifarrayentrycontainsazerovalue,theprocesswillacceptthedefaultactionofthe
signal.
Ifarrayentrycontainsa1value,theprocesswillignorethesignalandkernelwill
discardit.
Ifarrayentrycontainsanyothervalue,itisusedasthefunctionpointerforauser-
definedsignalhandlerroutine.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
243PROF. SYED MUSTAFA, HKBKCE
The function prototype of the signal APIis:
#include <signal.h>
void (*signal(intsig_no, void (*handler)(int)))(int);
Returns: previous disposition of signal (see following) if OK, SIG_ERR on error
The formal argument of the API are:
sig_nois a signal identifier like SIGINT or SIGTERM.
The handler argument is the function pointer of a user-defined signal handler function.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
244PROF. SYED MUSTAFA, HKBKCE
The function prototype of the signal APIis:
#include <signal.h>
void (*signal(intsig_no, void (*handler)(int)))(int);
The sig_noargument is just the name of the signal.
The value of handler is
(a)the constant SIG_IGN,
(b)the constant SIG_DFL, or
(c)the address of a function to be called when the signal occurs.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
245PROF. SYED MUSTAFA, HKBKCE
The function prototype of the signal APIis:
#include <signal.h>
void (*signal(intsig_no, void (*handler)(int)))(int);
IfwespecifySIG_IGN,wearetellingthesystemtoignorethesignal.
(RememberthatwecannotignorethetwosignalsSIGKILLandSIGSTOP)
WhenwespecifySIG_DFL,wearesettingtheactionassociatedwiththesignaltoits
defaultvalue.
Whenwespecifytheaddressofafunctiontobecalledwhenthesignaloccurs,weare
arrangingto"catch"thesignal.Wecallthefunctioneitherthesignalhandlerorthe
signal-catchingfunction.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
246PROF. SYED MUSTAFA, HKBKCE
The function prototype of the signal APIis:
#include <signal.h>
void (*signal(intsig_no, void (*handler)(int)))(int);
Theprototypeforthesignalfunctionstatesthatthefunctionrequirestwoarguments
andreturnsapointertoafunctionthatreturnsnothing(void).
Thesignalfunction'sfirstargument,sig_no,isaninteger.
Thesecondargumentisapointertoafunctionthattakesasingleintegerargumentand
returnsnothing.
Thefunctionwhoseaddressisreturnedasthevalueofsignaltakesasingleinteger
argument(thefinal(int)).
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
247PROF. SYED MUSTAFA, HKBKCE
The function prototype of the signal APIis:
#include <signal.h>
void (*signal(intsig_no, void (*handler)(int)))(int);
If we examine the system's header <signal.h>, we probably find declarations of the form
#define SIG_ERR (void (*)())-1
#define SIG_DFL (void (*)())0
#define SIG_IGN (void (*)())1
Theseconstantscanbeusedinplaceofthe"pointertoafunctionthattakesaninteger
argumentandreturnsnothing,"thesecondargumenttosignal,andthereturnvalue
fromsignal.
Thethreevaluesusedfortheseconstantsneednotbe-1,0,and1.
Theymustbethreevaluesthatcanneverbetheaddressofanydeclarablefunction.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
248PROF. SYED MUSTAFA, HKBKCE
ThefollowingexampleattemptstocatchtheSIGTERMsignal,ignorestheSIGINTsignal,
andacceptsthedefaultactionoftheSIGSEGVsignal.ThepauseAPIsuspendsthecalling
processuntilitisinterruptedbyasignalandthecorrespondingsignalhandlerdoesa
return:
#include<iostream.h>
#include<signal.h>
/*signal handler function*/
void catch_sig(intsig_num)
{
signal (sig_num,catch_sig);
cout<<”catch_sig:”<<sig_num<<endl;
}
intmain()/*main function*/
{
signal(SIGTERM,catch_sig);
signal(SIGINT,SIG_IGN);
signal(SIGSEGV,SIG_DFL);
pause( );/*wait for a signal interruption*/
}
The SIG_IGN specifies a signal is to be ignored, which means that if the signal is generated to the process,
it will be discarded without any interruption of theprocess.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
249PROF. SYED MUSTAFA, HKBKCE
#include<stdio.h>
#include<signal.h>
/*signal handler function*/
static void sig_usr(intsigno)
/* argis signal number */
{
if (signo== SIGUSR1)
printf("received SIGUSR1\n");
else if (signo== SIGUSR2)
printf("received SIGUSR2\n");
else
printf("received signal %d\n", signo);
}
intmain(void)
{
if (signal(SIGUSR1, sig_usr) == SIG_ERR)
perror("can't catch SIGUSR1");
if (signal(SIGUSR2, sig_usr) == SIG_ERR)
perror("can't catch SIGUSR2");
for ( ; ; )
pause();
}
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
250PROF. SYED MUSTAFA, HKBKCE
$ ./a.out& start process in background
[1] 7216 job-control shell prints job number and process ID
$ kill -USR1 7216 send it SIGUSR1
received SIGUSR1
$ kill -USR2 7216 send it SIGUSR2
received SIGUSR2
$ kill 7216 now send it SIGTERM
[1]+ Terminated ./a.out
When we send the SIGTERM signal, the process is terminated, since it doesn't catch the
signal, and the default action for the signal is termination.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
251PROF. SYED MUSTAFA, HKBKCE
kill and raise Functions
The kill function sends a signal to a process or a group of processes.
The raise function allows a process to send a signal to itself.
#include <signal.h>
int kill(pid_t pid, int signo);
intraise(intsigno);
Both return: 0 if OK, –1 on error
The call
raise(signo);
is equivalent to the call
kill(getpid(), signo);
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
252PROF. SYED MUSTAFA, HKBKCE
kill and raise Functions
#include <signal.h>
int kill(pid_t pid, int signo);
There are four different conditions for the pidargument to kill.
Pidvalue Meaning
Pid> 0The signal is sent to the process whose process ID is pid.
Pid==0The signal is sent to all processes whose process group ID equals the process
group ID of the sender and for which the sender has permission to send the
signal.
Pid<0 The signal is sent to all processes whose process group ID equals the absolute
value of pidand for which the sender has permission to send the signal.
Pid==-1The signal is sent to all processes on the system for which the sender has
permission to send the signal.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
254PROF. SYED MUSTAFA, HKBKCE
alarm and pause Functions
Thealarmfunctionallowsustosetatimerthatwillexpireataspecifiedtimeinthe
future.
Whenthetimerexpires,theSIGALRMsignalisgenerated.
Ifweignoreordon'tcatchthissignal,itsdefaultactionistoterminate
theprocess.
#include<unistd.h>
unsignedintalarm(unsignedintseconds);
Returns:0ornumberofsecondsuntilpreviouslysetalarm.
Thesecondsvalueisthenumberofclocksecondsinthefuturewhenthesignalshould
begenerated.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
255PROF. SYED MUSTAFA, HKBKCE
alarm and pause Functions
#include<unistd.h>
unsignedintalarm(unsignedintseconds);
If,whenwecallalarm,apreviouslyregisteredalarmclockfortheprocesshasnotyet
expired,thenumberofsecondsleftforthatalarmclockisreturnedasthevalueof
thisfunction.
Thatpreviouslyregisteredalarmclockisreplacedbythenewvalue.
Ifapreviouslyregisteredalarmclockfortheprocesshasnotyetexpiredandifthe
secondsvalueis0,thepreviousalarmclockiscanceled.
Thenumberofsecondsleftforthatpreviousalarmclockisstillreturnedasthevalue
ofthefunction.
AlthoughthedefaultactionforSIGALRMistoterminatetheprocess,mostprocesses
thatuseanalarmclockcatchthissignal.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
256PROF. SYED MUSTAFA, HKBKCE
alarm and pause Functions
Thepausefunctionsuspendsthecallingprocessuntilasignaliscaught.
#include <unistd.h>
intpause(void);
Returns: –1 with errnoset to EINTR
The only time pause returns is if a signal handler is executed and that handler returns.
In that case, pause returns –1 with errnoset to EINTR.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
257PROF. SYED MUSTAFA, HKBKCE
alarm and pause Functions
Usingalarmandpause,wecanputaprocesstosleepforaspecifiedamountoftime.
Thesleep()canbeimplementedusingalarm()andpause().
#include <signal.h>
#include <unistd.h>
static void sig_alrm(intsigno)
{
/* nothing to do, just return to
wake up the pause */
}
unsigned intsleep(unsigned intnsecs)
{
if (signal(SIGALRM, sig_alrm) == SIG_ERR)
return(nsecs);
alarm(nsecs); /* start the timer */
pause(); /* next caught signal wakes us up */
return(alarm(0));
/* turn off timer, return unslept time */
}
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
258PROF. SYED MUSTAFA, HKBKCE
SIGNAL SETS
We need a data type to represent multiple signals—a signal set
POSIX.1 defines the data type sigset_tto contain a signal set and the following five
functions to manipulate signal sets.
#include <signal.h>
intsigemptyset(sigset_t*set);
intsigfillset(sigset_t*set);
intsigaddset(sigset_t*set, intsigno);
int sigdelset(sigset_t *set, int signo);
Returns: 0 if OK, -1 on error.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
259PROF. SYED MUSTAFA, HKBKCE
SIGNAL SETS
intsigismember(constsigset_t*set, intsigno);
Returns: 1 if true, 0 if false, –1 on error
The function sigemptyset() initializes the signal set pointed to by set so that all signals
are excluded
The function sigfillset() initializes the signal set so that all signals are included.
All applications have to call either sigemptyset() or sigfillset() once for each signal set,
before using the signal set.
Once we have initialized a signal set, we can add and delete specific signals in the set.
The function sigaddset() adds a single signal to an existing set, and sigdelset()
removes a single signal from a set.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
260PROF. SYED MUSTAFA, HKBKCE
SIGNAL MASK
A process initially inherits the parent’s signal mask when it is created, but any pending
signals for the parent process are not passed on.
A process may query or set its signal mask via the sigprocmaskAPI:
#include <signal.h>
intsigprocmask(intcmd, constsigset_t*new_mask, sigset_t*old_mask);
Returns: 0 if OK, -1 on error
.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
261PROF. SYED MUSTAFA, HKBKCE
SIGNAL MASK
The new_maskargument defines a set of signals to be set or reset in a calling process
signal mask, and the cmdargument specifies how the new_maskvalue is to be used by
the API.
The possible values of cmdand the corresponding use of the new_maskvalue are:
.
Cmdvalue Meaning
SIG_SETMASK
Overrides the calling process signal mask with the value specified in the new_mask
argument.
SIG_BLOCK
Adds the signals specified in the new_maskargument to the calling process signal
mask.
SIG_UNBLOCK
Removes the signals specified in the new_maskargument from the calling process
signal mask.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
262PROF. SYED MUSTAFA, HKBKCE
SIGNAL MASK
The following example checks whether the SIGINT signal is present in a process signal mask
and adds it to the mask if it is not there. Then clears the SIGSEGV signal from the process
signal mask.
#include <stdio.h>
#include <signal.h>
intmain()
{
sigset_tmask;
sigemptyset(&mask);
/*initialize set*/
if (sigprocmask(0, 0, &mask) == -1)
{ /*get current signal mask*/
perror(“sigprocmask”);
exit(1);
}
else
sigaddset(&mask, SIGINT); /*set SIGINT flag*/
sigdelset(&mask, SIGSEGV);
/*clear SIGSEGV flag*/
if (sigprocmask(SIG_SETMASK, &mask, 0) == -1)
perror(“sigprocmask”);
/*set a new signal mask*/
} .
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
263PROF. SYED MUSTAFA, HKBKCE
SIGNAL MASK
The program prints the names of the signals in the signal mask of the calling process
#include <stdio.h>
#include <signal.h>
intmain()
{
sigset_tsigset;
sigemptyset(&sigset);
/*initialize set*/
if (sigprocmask(0, NULL, &sigset) < 0)
perror("sigprocmaskerror");
if (sigismember(&sigset, SIGINT))
printf("SIGINT ");
if (sigismember(&sigset, SIGQUIT))
printf("SIGQUIT ");
if (sigismember(&sigset, SIGUSR1))
printf("SIGUSR1 ");
if (sigismember(&sigset, SIGALRM))
printf("SIGALRM ");
}
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
264PROF. SYED MUSTAFA, HKBKCE
SIGPENDING FUNCTION
The sigpendingfunction returns the set of signals that are blocked from delivery and
currently pending for the calling process.
The set of signals is returned through the set argument
#include <signal.h>
intsigpending(sigset_t*set);
Returns: 0 if OK, –1 on error.
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
TheprocessblocksSIGQUIT,savingitscurrentsignalmask(toresetlater),
andthengoestosleepfor5seconds.
Anyoccurrenceofthequitsignalduringthisperiodisblockedandwon'tbe
delivereduntilthesignalisunblocked.
Attheendofthe5-secondsleep,wecheckwhetherthesignalispending
andunblockthesignal.
265PROF. SYED MUSTAFA, HKBKCE
SIGPENDING FUNCTION
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS -SIGPENDING FUNCTION
266PROF. SYED MUSTAFA, HKBKCE
#include <signal.h>
#include <unistd.h>
static void sig_quit(intsigno)
{
printf("caught SIGQUIT\n");
if (signal(SIGQUIT, SIG_DFL) == SIG_ERR)
perror("can't reset SIGQUIT");
}
intmain(void)
{
sigset_tnewmask, oldmask, pendmask;
if (signal(SIGQUIT, sig_quit) == SIG_ERR)
perror("can't catch SIGQUIT");
/* Block SIGQUIT and save current signal mask*/
sigemptyset(&newmask);
sigaddset(&newmask, SIGQUIT);
if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0)
perror("SIG_BLOCK error");
sleep(5);
/* SIGQUIT here will remain pending */
if (sigpending(&pendmask) < 0)
perror("sigpendingerror");
if (sigismember(&pendmask, SIGQUIT))
printf("\nSIGQUITpending\n");
/* Reset signal mask which unblocks SIGQUIT*/
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
perror("SIG_SETMASK error");
printf("SIGQUIT unblocked\n");
sleep(5);
/* SIGQUIT here will terminate with core file */
exit(0);
}
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
The sigaction() function allows us to examine or modify (or both) the action
associated with a particular signal.
This function supersedes the signal() function from earlier releases of the
UNIX System.
#include <signal.h>
intsigaction(intsigno, conststructsigaction*restrict act,
structsigaction*restrict oact);
Returns: 0 if OK, –1 on error
267PROF. SYED MUSTAFA, HKBKCE
Sigaction() Function
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
sigaction() Function
The sigactionAPI is a replacement for the signal API in the latest UNIX and
POSIX systems.
The sigactionAPI is called by a process to set up a signal handling method
for each signal it wants to deal with.
sigactionAPI returns the previous signal handling method for a given signal.
268PROF. SYED MUSTAFA, HKBKCE
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
sigaction() Function
The structsigactiondata type is defined in the <signal.h> header as
structsigaction
{
void (*sa_handler)(int); /* addr of signal handler,or SIG_IGN, or SIG_DFL */
sigset_tsa_mask; /* additional signals to block */
intsa_flags; /* signal options */
void(*sa_sigaction)(int, siginfo_t*, void*); /* alternate handler */
};
269PROF. SYED MUSTAFA, HKBKCE
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
sigaction() Function
Thesa_handlerfieldcanbesettoSIG_IGN,SIG_DFL,orauserdefined
signalhandlerfunction.
Thesa_maskfieldspecifiesadditionalsignalsthatprocesswishestoblock
whenitishandlingsignosignal.
Thesignalnoargumentdesignateswhichsignalhandlingactionisdefinedin
theactionargument.
Theprevioussignalhandlingmethodforsignalnowillbereturnedviathe
oldactionargumentifitisnotaNULLpointer.
IfactionargumentisaNULLpointer,thecallingprocess‘sexistingsignal
handlingmethodforsignalnowillbeunchanged.
270PROF. SYED MUSTAFA, HKBKCE
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS -sigactionFUNCTION
In the program, the process signal mask is set with SIGTERM signal.
The process then defines a signal handler for the SIGINT signal and also
specifies that the SIGSEGV signal is to be blocked when the process is
handling the SIGINT signal.
The process then terminates its execution via the pause API.
The output of the program would be as:
% cc sigaction.c–o sigaction
% ./sigaction&
[1] 495
% kill –INT 495
catch signal: 2
sigactionexits
[1] Done sigaction
272PROF. SYED MUSTAFA, HKBKCE
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
THE SIGCHLD SIGNAL AND THE waitpidAPI
When a child process terminates or stops, the kernel will generate a SIGCHLD signal to its
parent process. Depending on how the parent sets up the handling of the SIGCHLD signal,
different events may occur:
1. Parent accepts the default action of the SIGCHLD signal:
SIGCHLD does not terminate the parent process.
Parent process will be awakened.
API will return the child’s exit status and process ID to the parent.
Kernel will clear up the Process Table slot allocated for the child process.
Parent process can call the waitpidAPI repeatedly to wait for each child it created.
273PROF. SYED MUSTAFA, HKBKCE
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
THE SIGCHLD SIGNAL AND THE waitpidAPI
2. Parent ignores the SIGCHLD signal:
SIGCHLD signal will be discarded.
Parent will not be disturbed even if it is executing the waitpidsystem call.
If the parent calls the waitpidAPI, the API will suspend the parent until all its child
processes have terminated.
Child process table slots will be cleared up by the kernel.
API will return a -1 value to the parent process.
3. Process catches the SIGCHLD signal:
The signal handler function will be called in the parent process whenever a child process
terminates.
If the SIGCHLD arrives while the parent process is executing the waitpidsystem call, the
waitpidAPI may be restarted to collect the child exit status and clear its process table
slots.
Depending on parent setup, the API may be aborted and child process table slot not
freed.
274PROF. SYED MUSTAFA, HKBKCE
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
abort() Function
abort function causes abnormal program termination
#include <stdlib.h>
void abort(void);
This function never returns.
This function sends the SIGABRT signal to the caller.
Processes should not ignore this signal.
ISO C states that calling abort will deliver an unsuccessful termination notification to the
host environment by calling raise(SIGABRT).
275PROF. SYED MUSTAFA, HKBKCE
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
system() Function
#include <stdlib.h>
intsystem(constchar *command);
This function returns is -1 on error.
If the value ofcommandis NULL,system() returns nonzero if the shell is available, and zero
if not.
system() executes a command specified incommandby calling/bin/sh-ccommand, and
returns after the command has been completed. During execution of the
command,SIGCHLDwill be blocked, andSIGINTandSIGQUITwill be ignored
Eg: system(“ls –l”);
276PROF. SYED MUSTAFA, HKBKCE
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
sleep() Function
sleep -sleep for the specified number of seconds
#include <unistd.h>
unsigned intsleep(unsigned intseconds);
Returns: 0 or number of unslept seconds.
This function causes the calling process to be suspended until either
1. The amount of wall clock time specified by seconds has elapsed.
2. A signal is caught by the process and the signal handler returns.
Eg:
sleep(60); // suspend the process for one minute.
277PROF. SYED MUSTAFA, HKBKCE
UNIT 6 SIGNALS AND DAEMON PROCESSES
SIGNALS
Job-Control Signals
POSIX.1 considers six signals as job-control signals:
278PROF. SYED MUSTAFA, HKBKCE
Signal Meaning
SIGCHLDChild process has stopped or terminated.
SIGCONTContinue process, if stopped.
SIGSTOPStop signal (can't be caught or ignored).
SIGTSTPInteractive stop signal.
SIGTTINRead from controlling terminal by member of a background process
group
SIGTTOU Write to controlling terminal by member of a background process group
UNIT 6 SIGNALS AND DAEMON PROCESSES
DAEMON PROCESSES
Daemonsareprocessesthatliveforalongtime.
Theyareoftenstartedwhenthesystemisbootstrappedandterminateonlywhenthe
systemisshutdown.
Becausetheydon'thaveacontrollingterminal,wesaythattheyruninthebackground.
UNIXsystemshavenumerousdaemonsthatperformday-to-dayactivities.
280PROF. SYED MUSTAFA, HKBKCE
UNIT 6 SIGNALS AND DAEMON PROCESSES
DAEMON PROCESSES
DeamonCharacteristics
$ps-axj
281PROF. SYED MUSTAFA, HKBKCE
UNIT 6 SIGNALS AND DAEMON PROCESSES
DAEMON PROCESSES
DeamonCharacteristics
Daemons run in background.
Daemons have super-user privilege.
Daemons don’t have controlling terminal.
Daemons are session and group leaders.
282PROF. SYED MUSTAFA, HKBKCE