Unix system programming

syedmustafablr 8,841 views 178 slides Mar 15, 2016
Slide 1
Slide 1 of 291
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170
Slide 171
171
Slide 172
172
Slide 173
173
Slide 174
174
Slide 175
175
Slide 176
176
Slide 177
177
Slide 178
178
Slide 179
179
Slide 180
180
Slide 181
181
Slide 182
182
Slide 183
183
Slide 184
184
Slide 185
185
Slide 186
186
Slide 187
187
Slide 188
188
Slide 189
189
Slide 190
190
Slide 191
191
Slide 192
192
Slide 193
193
Slide 194
194
Slide 195
195
Slide 196
196
Slide 197
197
Slide 198
198
Slide 199
199
Slide 200
200
Slide 201
201
Slide 202
202
Slide 203
203
Slide 204
204
Slide 205
205
Slide 206
206
Slide 207
207
Slide 208
208
Slide 209
209
Slide 210
210
Slide 211
211
Slide 212
212
Slide 213
213
Slide 214
214
Slide 215
215
Slide 216
216
Slide 217
217
Slide 218
218
Slide 219
219
Slide 220
220
Slide 221
221
Slide 222
222
Slide 223
223
Slide 224
224
Slide 225
225
Slide 226
226
Slide 227
227
Slide 228
228
Slide 229
229
Slide 230
230
Slide 231
231
Slide 232
232
Slide 233
233
Slide 234
234
Slide 235
235
Slide 236
236
Slide 237
237
Slide 238
238
Slide 239
239
Slide 240
240
Slide 241
241
Slide 242
242
Slide 243
243
Slide 244
244
Slide 245
245
Slide 246
246
Slide 247
247
Slide 248
248
Slide 249
249
Slide 250
250
Slide 251
251
Slide 252
252
Slide 253
253
Slide 254
254
Slide 255
255
Slide 256
256
Slide 257
257
Slide 258
258
Slide 259
259
Slide 260
260
Slide 261
261
Slide 262
262
Slide 263
263
Slide 264
264
Slide 265
265
Slide 266
266
Slide 267
267
Slide 268
268
Slide 269
269
Slide 270
270
Slide 271
271
Slide 272
272
Slide 273
273
Slide 274
274
Slide 275
275
Slide 276
276
Slide 277
277
Slide 278
278
Slide 279
279
Slide 280
280
Slide 281
281
Slide 282
282
Slide 283
283
Slide 284
284
Slide 285
285
Slide 286
286
Slide 287
287
Slide 288
288
Slide 289
289
Slide 290
290
Slide 291
291

About This Presentation

6th semester Unix System Programming


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

Commonlyoccurerrorstatuscodesandtheirmeanings
15PROF. 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
•Device file
Majordevicenumber:
Itisanindextoakerneltablethatcontainstheaddressesofalldevicedriver
functionsknowntothesystem.
Wheneveraprocessreadsdatafromorwritesdatatoadevicefile,thekerneluses
thedevicefile’smajornumbertoselectandinvokeadevicedriverfunctiontocarry
outactualdatatransferwithaphysicaldevice.
Minordevicenumber:
Itisanintegervaluetobepassedasanargumenttoadevicedriverfunctionwhen
itiscalled.
Ittellsthedevicedriverfunctionwhatactualphysicaldeviceistalkingtoandthe
I/Obufferingschemetobeusedfordatatransfer.
20PROF. 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
23PROF. SYED MUSTAFA, HKBKCE

UNIT 2 UNIX FILES
24PROF. SYED MUSTAFA, HKBKCE

UNIT 2 UNIX FILES
TheUNIXandPOSIXFileAttributes
Thegeneralfileattributesforeachfileinafilesystemare:
1)Filetype -specifieswhattypeoffileitis.
2)Accesspermission-thefileaccesspermissionforowner,groupandothers.
3)Hardlinkcount-numberofhardlinkofthefile
4)Uid -thefileowneruserid.
5)Gid -thefilegroupid.
6)Filesize -thefilesizeinbytes.
7)Inodeno -thesysteminodenoofthefile.
8)Filesystemid -thefilesystemidwherethefileisstored.
25PROF. 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
GenerallyanOSdoesnotkeepthenameofafileinitsrecord,becausethe
mappingofthefilenamestoinodenoisdoneviadirectoryfilesi.e.adirectory
filecontainsalistofnamesoftheirrespectiveinodeno.forallfilestoredinthat
directory.
Ex:asampledirectoryfilecontent
Inodesin UNIX SystemV
Inodenumber Filename
115 .
89 ..
201 xyz
346 a.out
201 xyz_lnk
29PROF. SYED MUSTAFA, HKBKCE

UNIT 2 UNIX FILES
Inodesin UNIX SystemV
Toaccessafile,forexample/usr/syed,theUNIXkernelalways
knowsthe“/”(root)directoryinodenumberofanyprocess.
Itwillscanthe“/”directoryfiletofindtheinodenumberofthe
usrfile.Onceitgetstheusrfileinodenumber,itaccessesthe
contentsofusrfile.Itthenlooksfortheinodenumberofsyed
file.
Wheneveranewfileiscreatedinadirectory,theUNIXkernel
allocatesanewentryintheinodetabletostoretheinformation
ofthenewfile
Itwillassignauniqueinodenumbertothefileandaddthenew
filenameandinodenumbertothedirectoryfilethatcontainsit.
30PROF. 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
Application Programming Interface to Files
Foranyapplicationtoaccessfiles,firstitshouldbeopened.
Generallyweuseopensystemcalltoopenafile,andthe
returnedvalueisanintegerwhichistermedasfiledescriptor.
Therearecertainlimitsofaprocesstoopenfiles.
AmaximumnumberofOPEN-MAXfilescanbeopened.The
valueisdefinedin<limits.h>header.
Thedatatransferfunctiononanyopenedfileiscarriedoutby
readandwritesystemcall.
32PROF. SYED MUSTAFA, HKBKCE

UNIT 2 UNIX FILES
Application Programming Interface to Files
Filehardlinkscanbeincreasedbylinksystemcall,and
decreasedbyunlinksystemcall.
Fileattributescanbechangedbychown,chmodandlink
systemcalls.
Fileattributescanbequeried(foundoutorretrieved)bystat
andfstatsystemcall.
UNIXandPOSIX.1definesastructureofdatatypestati.e.
definedin<sys/stat.h>headerfile.Thiscontainstheuser
accessibleattributeofafile.
33PROF. SYED MUSTAFA, HKBKCE

UNIT 2 UNIX FILES
34PROF. 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 ( )
Thereadfunctionfetchesafixedsizeofblockofdatafromafilereferencedbya
givenfiledescriptor.
Theprototypeofreadfunctionis:
#include<sys/types.h>
#include<unistd.h>
size_tread(intfdesc,void*buf,size_tnbyte);
Ifsuccessful,readreturnstheno.ofbytesactuallyread,onerroritreturns–1.
Thefirstargumentisaninteger,fdescthatreferstoanopenedfile.
Thesecondargument,bufistheaddressofabufferholdinganydataread.
Thethirdargumentspecifieshowmanybytesofdataaretobereadfromthe
file.
Thesize_tdatatypeisdefinedinthe<sys/types.h>headerandshouldbethe
sameasunsignedint.
64PROF. 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
read ( )
#include<fcntl.h>
intmain()
{
intfd,nob;charc[256];
fd=open(“sample”,O_RDONLY);
nob=read(fd,c,sizeof(c));
if(nob!=-1)
printf("%s\n",c);
else
perror(“read Error”);
close(fd);
return 0;
}
67PROF. 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
Emulate ‘cp’ UNIX command –cpf1 f2
#include<fcntl.h>
intmain()
{
intfd1,fd2,nob;
char c;
fd1=open(“f1”,O_RDONLY);
fd2=open(“f2”,O_WRONLY|)_CREAT|O_TRUNC, 0777);
while(read(fd1,&c,1))
write(fd2,&c,1);
close(fd1);
close(fd2);
return 0;
}
73PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIs
Emulate ‘cp’ UNIX command –cpf1 f2
#include<fcntl.h>
intmain()
{
intfd1,fd2,nob;
char c;
fd1=open(“f1”,O_RDONLY);
If(fd1!=-1)
{ fd2=open(“f2”,O_WRONLY|)_CREAT|O_TRUNC, 0777);
if(fd2!=-1)
{ while(read(fd1,&c,1))
write(fd2,&c,1);
close(fd1);
close(fd2);
}
else
{
perror(“write Error”);
close(fd1);
}
} /*if fd1 */
else
perror(“read Error”);
return 0;
}
74PROF. 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
Chmod(), fchmod()
Thepathnameargumentofchmodisthepathnameofafilewhereasthefdescargumentoffchmodis
thefiledescriptorofafile.
Thechmodfunctionoperatesonthespecifiedfile,whereasthefchmod()functionoperatesonafile
thathasalreadybeenopened.
Tochangethepermissionbitsofafile,theeffectiveuserIDoftheprocessmustbeequaltotheowner
IDofthefile,ortheprocessmusthavesuper-userpermissions.ThemodeisspecifiedasthebitwiseOR
oftheconstantsshownbelow
90PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIs
91PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIs
92PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIs
93PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIs
94PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIs
95PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIs
96PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIs
97PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIs
File and Record Locking
Multipleprocessesperformsreadandwriteoperationonthe
samefileconcurrently.
Thisprovidesameansfordatasharingamongprocesses,butit
alsorendersdifficultyforanyprocessindeterminingwhenthe
otherprocesscanoverridedatainafile.
So,inordertoovercomethisdrawbackUNIXandPOSIXstandard
supportfilelockingmechanism.
Filelockingisapplicableforregularfiles.
98PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIs
File and Record Locking
Onlyaprocesscanimposeawritelockorreadlockoneitheraportionofa
fileorontheentirefile.
Thedifferencesbetweenthereadlockandthewritelockisthatwhenwrite
lockisset,itpreventstheotherprocessfromsettinganyover-lappingread
orwritelockonthelockedfile.
Similarlywhenareadlockisset,itpreventsotherprocessesfromsetting
anyoverlappingwritelocksonthelockedregion.
Theintensionofthewritelockistopreventotherprocessesfromboth
readingandwritingthelockedregionwhiletheprocessthatsetsthelockis
modifyingtheregion,sowritelockistermedas“Exclusivelock”.
99PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIs
File and Record Locking
Theuseofreadlockistopreventotherprocessesfromwritingtothe
lockedregionwhiletheprocessthatsetsthelockisreadingdatafromthe
region.
Otherprocessesareallowedtolockandreaddatafromthelockedregions.
Henceareadlockisalsocalledas“sharedlock“.
Filelockmaybemandatoryiftheyareenforcedbyanoperatingsystem
kernel.
Ifamandatoryexclusivelockissetonafile,noprocesscanusethereador
writesystemcallstoaccessthedataonthelockedregion.
Thesemechanismscanbeusedtosynchronizereadingandwritingof
sharedfilesbymultipleprocesses.
100PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIs
File and Record Locking
Ifaprocesslocksupafile,otherprocessesthatattempttowritetothe
lockedregionsareblockeduntiltheformerprocessreleasesitslock.
Problemwithmandatorylockis–ifarunawayprocesssetsamandatory
exclusivelockonafileandneverunlocksit,then,nootherprocesscan
accessthelockedregionofthefileuntiltherunwayprocessiskilledorthe
systemhastoberebooted.
Iflocksarenotmandatory,thenithastobeadvisorylock.
Akernelatthesystemcallleveldoesnotenforceadvisorylocks.
Thismeansthateventhoughalockmaybesetonafile,nootherprocesses
canstillusethereadandwritefunctionstoaccessthefile.
101PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIs
File and Record Locking
Tomakeuseofadvisorylocks,processthatmanipulatethesamefilemustco-
operatesuchthattheyfollowthegivenbelowprocedureforeveryreador
writeoperationtothefile.
1.Trytosetalockattheregiontobeaccesses.Ifthisfails,aprocesscan
eitherwaitforthelockrequesttobecomesuccessful.
2.Afteralockisacquiredsuccessfully,readorwritethelockedregion.
3.Releasethelock.
102PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIsFileandRecordLocking
Ifaprocesssetsareadlockonafile,forexamplefromaddress0to256,
thensetsawritelockonthefilefromaddress0to512,theprocesswill
ownonlyonewritelockonthefilefrom0to512,thepreviousreadlock
from0to256isnowcoveredbythewritelockandtheprocessdoesnot
owntwolocksontheregionfrom0to256.Thisprocessiscalled“Lock
Promotion”.
Furthermore,ifaprocessnowunblocksthefilefrom128to480,itwillown
twowritelocksonthefile:
onefrom0to127andtheotherfrom481to512.Thisprocessiscalled
“LockSplitting”.
UNIXsystemsprovidefcntlfunctiontosupportfilelocking.
Byusingfcntlitispossibletoimposereadorwritelocksoneitheraregion
oranentirefile.
103PROF. 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
utime()
Thetime_tdatatypeisanunsignedlonganditsdataisthenumberoftheseconds
elapsedsincethebirthdayofUNIX:12AM,Jan1of1970.
Ifthetimes(variable)isspecifiedasNULL,thefunctionwillsetthenamedfileaccess
andmodificationtimetothecurrenttime.
Ifthetimes(variable)isanaddressofthevariableofthetypestructutimbuf,the
functionwillsetthefileaccesstimeandmodificationtimetothevaluespecifiedbythe
variable.
110PROF. 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
Devicefilesareusedtointerfacephysicaldevicewithapplicationprograms.
AprocesswithsuperuserprivilegestocreateadevicefilemustcallthemknodAPI.
TheuserIDandgroupIDattributesofadevicefileareassignedinthesamemanneras
forregularfiles.
Whenaprocessreadsorwritestoadevicefile,thekernelusesthemajorandminor
devicenumbersofafiletoselectadevicedriverfunctiontocarryouttheactualdata
transfer.
Devicefilesupportisimplementationdependent.UNIXSystemdefinesthemknodAPIto
createdevicefiles.
Theprototypeofmknodis
#include<sys/stat.h>
#include<unistd.h>
intmknod(constchar* path_name, mode_tmode, intdevice_id);
117PROF. 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
Example
mkfifo(“FIFO5”, S_IFIFO | S_IRWXU | S_IRGRP | S_ROTH);
TheabovestatementcreatesaFIFOfile“fifo5”withread-write-executepermissionfor
userandonlyreadpermissionforgroupandothers.
OncewehavecreatedaFIFOusingmkfifo,weopenitusingopen.
Indeed,thenormalfileI/Ofunctions(read,write,unlinketc)allworkwithFIFOs.
WhenaprocessopensaFIFOfileforreading,thekernelwillblocktheprocessuntilthere
isanotherprocessthatopensthesamefileforwriting.
SimilarlywheneveraprocessopensaFIFOfilewrite,thekernelwillblocktheprocess
untilanotherprocessopensthesameFIFOforreading.
Thisprovidesameansforsynchronizationinordertoundergointer-process
communication.
IfaparticularprocesstriestowritesomethingtoaFIFOfilethatisfull,thenthatprocess
willbeblockeduntilanotherprocesshasreaddatafromtheFIFOtomakespaceforthe
processtowrite.
121PROF. SYED MUSTAFA, HKBKCE

UNIT 3 UNIX FILE APIs
FIFO file API’s
Similarly,ifaprocessattemptstoreaddatafromanemptyFIFO,theprocesswillbe
blockeduntilanotherprocesswritesdatatotheFIFO.
Fromanyoftheaboveconditioniftheprocessdoesn’twanttogetblockedthenwe
shouldspecifyO_NONBLOCKintheopencalltotheFIFOfile.
Ifthedataisnotreadyforread/writethenopenreturns–1insteadofprocessgetting
blocked.
IfaprocesswritestoaFIFOfilethathasnootherprocessattachedtoitforread,the
kernelwillsendSIGPIPEsignaltotheprocesstonotifythatitisanillegaloperation.
AnothermethodtocreateFIFOfiles(notexactly)forinter-processcommunicationisto
usethepipesystemcall.
122PROF. 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 3 UNIX FILE APIs
intfd; char buf[256];
(void) mkfifo(argv[1], S_IFIFO | S_IRWXU | S_IRWXG | S_IRWXO );
if(argc==2)
{
fd=open(argv[1],O_RDONLY | O_NONBLOCK);
while(read(fd,buf,sizeof(buf))==-1 && errno==EAGAIN)
sleep(1);
while(read(fd,buf,sizeof(buf))>0)
cout<<buf<<endl;
}
else
{
fd=open(argv[1],O_WRONLY);
write(fd,argv[2],strlen(argv[2]));
}
close(fd);
}
125PROF. 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
ISOCspecifiesthreefunctionsformemoryallocation:
malloc:
whichallocatesaspecifiednumberofbytesofmemory.Theinitialvalueofthememoryis
indeterminate.
calloc:
whichallocatesspaceforaspecifiednumberofobjectsofaspecifiedsize.
Thespaceisinitializedtoall0bits.
realloc:
whichincreasesordecreasesthesizeofapreviouslyallocatedarea.
Whenthesizeincreases,itmayinvolvemovingthepreviouslyallocatedareasomewhere
else,toprovidetheadditionalroomattheend.Also,whenthesizeincreases,theinitial
valueofthespacebetweentheoldcontentsandtheendofthenewareaisindeterminate.
140PROF. 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
Setjmp() & longjmp() FUNCTIONS
1.Thesetjmpfunctionalwaysreturns‘0’onitssuccesswhenitiscalleddirectlyina
process(forthefirsttime).
2.Thelongjmpfunctioniscalledtotransferaprogramflowtoalocationthatwasstoredin
theenvargument.
3.Theprogramcodemarkedbytheenvmustbeinafunctionthatisamongthecallersof
thecurrentfunction.
4.Whentheprocessisjumpingtothetargetfunction,allthestackspaceusedinthe
currentfunctionanditscallers,uptothetargetfunctionarediscardedbythelongjmp
function.
5.Theprocessresumesexecutionbyre-executingthesetjmpstatementinthetarget
functionthatismarkedbyenv.
6.Thereturnvalueofsetjmpfunctionisthevalue(val),asspecifiedinthelongjmp
functioncall.
7.The‘val’shouldbenonzero,sothatitcanbeusedtoindicatewhereandwhythe
longjmpfunctionwasinvokedandprocesscandoerrorhandlingaccordingly.
148PROF. SYED MUSTAFA, HKBKCE

UNIT 4 UNIX PROCESSES
Setjmp() & longjmp() FUNCTIONS
#include <stdio.h>
#include <setjmp.h>
jmp_bufjb;
intmain(intargc, char *argv[])
{
inta, b, c;
printf("Give two numbers for division : ");
scanf("%d %d", &a, &b);
if(setjmp(jb) == 0)
{
c = division(a, b);
printf("%d / %d = %d", a, b, c);
return 0;
}
else
{
handle_error();
return -1;
}
}
intdivision(inta, intb)
{
if(b == 0)
longjmp(jb, 1);
else
return (a/b);
}
void handle_error(void)
{
printf("Divide by zero error !");
}
149PROF. 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 CONTROLexec() Functions
Thefirstdifferenceinthesefunctionsisthatthefirstfourtakeapathnameargument,
whereasthelasttwotakeafilenameargument.
Whenafilenameargumentisspecified
Iffilenamecontainsaslash,itistakenasapathname.
Otherwise,theexecutablefileissearchedforinthedirectoriesspecifiedbythePATH
environmentvariable.
Thenextdifferenceconcernsthepassingoftheargumentlist(lstandsforlistandvstandsfor
vector).Thefunctionsexecl,execlp,andexeclerequireeachofthecommand-linearguments
tothenewprogramtobespecifiedasseparatearguments.
Fortheotherthreefunctions(execv,execvp,andexecve),wehavetobuildanarrayof
pointerstothearguments,andtheaddressofthisarrayistheargumenttothesethree
functions.
Thefinaldifferenceisthepassingoftheenvironmentlisttothenewprogram.
Thetwofunctionswhosenamesendinane(execleandexecve)allowustopassapointerto
anarrayofpointerstotheenvironmentstrings.
Theotherfourfunctions,however,usetheenvironvariableinthecallingprocesstocopythe
existingenvironmentforthenewprogram.
183PROF. 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
253PROF. SYED MUSTAFA, HKBKCE
#include<iostream.h>
#include<signal.h>
/*signal handler function*/
void catch_sig(intsig_num)
{
cout<<”catch_sig:”<<sig_num<<endl;
}
intmain()/*main function*/
{
signal (SIGINT,catch_sig);
cout<<“from main\n”;
kill(getpid, SIGINT);
}
#include<iostream.h>
#include<signal.h>
/*signal handler function*/
void catch_sig(intsig_num)
{
cout<<”catch_sig:”<<sig_num<<endl;
}
intmain()/*main function*/
{
signal (SIGQUIT,catch_sig);
cout<<“from main\n”;
raise(SIGQUIT);
}

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
271PROF. SYED MUSTAFA, HKBKCE
#include <signal.h>
#include <iostream.h>
void callme( intsig_num)
{
cout<<“catch signal:”<<sig_num<< endl;
}
intmain(void)
{
sigset_tsigmask;
structsigactionaction, old_action;
sigemptyset(&sigmask);
if ( sigaddset( &sigmask, SIGTERM) == -1 ||
sigprocmask( SIG_SETMASK, &sigmask, 0) == -1)
perror(“Set signal mask”);
sigemptyset( &action.sa_mask);
sigaddset( &action.sa_mask, SIGSEGV);
action.sa_handler= callme;
action.sa_flags= 0;
if (sigaction(SIGINT, &action, &old_action) == -1)
perror(“sigaction”);
pause(); /* wait for signal interruption*/
return 0;
}

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
SIGNALS
Job-Control Signals
Whenwetypethesuspendcharacter(usuallyControl-Z),SIGTSTPissenttoallprocesses
intheforegroundprocessgroup.
Whenwetelltheshelltoresumeajobintheforegroundorbackground,theshellsends
alltheprocessesinthejobtheSIGCONTsignal.
Similarly,ifSIGTTINorSIGTTOUisdeliveredtoaprocess,theprocessisstoppedby
default,andthejob-controlshellrecognizesthisandnotifiesus.
Whenanyofthefourstopsignals(SIGTSTP,SIGSTOP,SIGTTIN,orSIGTTOU)isgenerated
foraprocess,anypendingSIGCONTsignalforthatprocessisdiscarded.
Similarly,whentheSIGCONTsignalisgeneratedforaprocess,anypendingstopsignals
forthatsameprocessarediscarded.
ThedefaultactionforSIGCONTistocontinuetheprocess,ifitisstopped;otherwise,the
signalisignored.
279PROF. SYED MUSTAFA, HKBKCE

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

UNIT 6 SIGNALS AND DAEMON PROCESSES
DAEMON PROCESSES
DeamonCharacteristics
AnythingwithaparentprocessIDof0isusuallyakernelprocessstartedaspartofthe
systembootstrapprocedure.
Kernelprocessesarespecialandgenerallyexistfortheentirelifetimeofthesystem.
Theyrunwithsuperuserprivilegesandhavenocontrollingterminalandnocommand
line.
ProcessIDof1isusuallyinit.
Itisasystemdaemonresponsiblefor,amongotherthings,startingsystemservices
specifictovariousrunlevels.
283PROF. SYED MUSTAFA, HKBKCE

UNIT 6 SIGNALS AND DAEMON PROCESSES
DAEMON PROCESSES
DeamonCharacteristics
keventddaemonprovidesprocesscontextforrunningscheduledfunctionsinthekernel.
Thekapmddaemonprovidessupportfortheadvancedpowermanagementfeatures
availablewithvariouscomputersystems.
Thekswapddaemonisalsoknownasthepageoutdaemon.
Itsupportsthevirtualmemorysubsystembywritingdirtypagestodiskslowlyovertime,
sothepagescanbereclaimed.
Theinetddaemon(xinetd)listensonthesystem'snetworkinterfacesforincoming
requestsforvariousnetworkservers.
Thenfsd,lockd,andrpcioddaemonsprovidesupportforthe
NetworkFileSystem(NFS).
Thecrondaemon(crond)executescommandsatspecifieddatesandtimes.Numerous
systemadministrationtasksarehandledbyhavingprogramsexecutedregularlybycron.
Thecupsddaemonisaprintspooler;ithandlesprintrequestsonthesystem.
284PROF. SYED MUSTAFA, HKBKCE

UNIT 6 SIGNALS AND DAEMON PROCESSES
DAEMON PROCESSES
CODING RULES
1.Callumasktosetthefilemodecreationmaskto0.Thefilemodecreation
maskthat'sinheritedcouldbesettodenycertainpermissions.Ifthe
daemonprocessisgoingtocreatefiles,itmaywanttosetspecific
permissions.
2.Callforkandhavetheparentexit.Thisdoesseveralthings.First,ifthe
daemonwasstartedasasimpleshellcommand,havingtheparent
terminatemakestheshellthinkthatthecommandisdone.Second,the
childinheritstheprocessgroupIDoftheparentbutgetsanewprocessID,
sowe'reguaranteedthatthechildisnotaprocessgroupleader.
285PROF. SYED MUSTAFA, HKBKCE

UNIT 6 SIGNALS AND DAEMON PROCESSESDAEMON PROCESSES
CODING RULES
3.Callsetsidtocreateanewsession.Theprocess(a)becomesasession
leaderofanewsession,(b)becomestheprocessgroupleaderofanew
processgroup,and(c)hasnocontrollingterminal.
4.Changethecurrentworkingdirectorytotherootdirectory.Thecurrent
workingdirectoryinheritedfromtheparentcouldbeonamountedfile
system.Sincedaemonsnormallyexistuntilthesystemisrebooted,ifthe
daemonstaysonamountedfilesystem,thatfilesystemcannotbe
unmounted.
5.Unneededfiledescriptorsshouldbeclosed.Thispreventsthedaemon
fromholdingopenanydescriptorsthatitmayhaveinheritedfromits
parent.
286PROF. SYED MUSTAFA, HKBKCE

UNIT 6 SIGNALS AND DAEMON PROCESSES
DAEMON PROCESSES
CODING RULES
6.Somedaemonsopenfiledescriptors0,1,and2to/dev/nullsothatany
libraryroutinesthattrytoreadfromstandardinputorwritetostandard
outputorstandarderrorwillhavenoeffect.Sincethedaemonisnot
associatedwithaterminaldevice,thereisnowhereforoutputtobe
displayed;noristhereanywheretoreceiveinputfromaninteractiveuser.
Evenifthedaemonwasstartedfromaninteractivesession,thedaemon
runsinthebackground,andtheloginsessioncanterminatewithout
affectingthedaemon.Ifotherusersloginonthesameterminaldevice,we
wouldn'twantoutputfromthedaemonshowingupontheterminal,and
theuserswouldn'texpecttheirinputtobereadbythedaemon.
287PROF. SYED MUSTAFA, HKBKCE

UNIT 6 SIGNALS AND DAEMON PROCESSES
DAEMON PROCESSES
CODING RULES
Example Program:
288PROF. SYED MUSTAFA, HKBKCE
#include <unistd,h>
#include <sys/types.h>
#include <fcntl.h>
intdaemon_initialise( )
{
pid_tpid;
if (( pid= fork() ) < 0)
return –1;
else if ( pid!= 0)
exit(0);/* parent exits */
/* child continues */
setsid( );
chdir(“/”);
umask(0);
return 0;
}

UNIT 6 SIGNALS AND DAEMON PROCESSES
DAEMON PROCESSES
Error Logging
Oneproblemadaemonhasishowtohandleerrormessages.
Itcan'tsimplywritetostandarderror,sinceitshouldn'thaveacontrolling
terminal.
Wedon'twantallthedaemonswritingtotheconsoledevice,sinceon
manyworkstations,theconsoledevicerunsawindowingsystem.
Wealsodon'twanteachdaemonwritingitsownerrormessagesintoa
separatefile.
Acentraldaemonerrorloggingfacilityisrequired.
289PROF. SYED MUSTAFA, HKBKCE

UNIT 6 SIGNALS AND DAEMON PROCESSES
DAEMON PROCESSES
Error Logging
290PROF. SYED MUSTAFA, HKBKCE

UNIT 6 SIGNALS AND DAEMON PROCESSES
DAEMON PROCESSES
Error Logging
Therearethreewaystogeneratelogmessages:
1.Kernelroutinescancallthelogfunction.
Thesemessagescanbereadbyanyuserprocessthatopensandreadsthe
/dev/klogdevice.
2.Mostuserprocesses(daemons)callthesyslog(3)functiontogeneratelog
messages.ThiscausesthemessagetobesenttotheUNIXdomaindatagram
socket/dev/log.
3.Auserprocessonthishost,oronsomeotherhostthatisconnectedtothis
hostbyaTCP/IPnetwork,cansendlogmessagestoUDPport514.
Thesyslogddaemonreadsallthreeformsoflogmessages.
Onstart-up,thisdaemonreadsaconfigurationfile,usually/etc/syslog.conf,
whichdetermineswheredifferentclassesofmessagesaretobesent.
291PROF. SYED MUSTAFA, HKBKCE