0% found this document useful (0 votes)
36 views16 pages

CSE 325 Lab Programs

Lab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views16 pages

CSE 325 Lab Programs

Lab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Pr

ogr
am1:
Towr
it
esomedat
aont
hest
andar
dout
putdev
ice(
bydef
aul
t–moni
tor
)

/
/Namet
hepr
ogr
am f
il
eas“
wri
te.
c”

#i
nclude<unistd.
h>
i
ntmai n()
{
wri
te(1,
"hell
o\n",
6);/
/1i
sthef
il
edescr
ipt
or,"
hel
l
o\n"i
sthedat
a,6i
sthecountofchar
act
ers
i
ndat a
}

Pr
ogr
am 2

#incl
ude<stdio.h
#incl
ude<unistd.h>
i
ntmai n()
{
i
ntcount ;
count=writ
e(1,"
hell
o\n",
6);
print
f("
Totalbyteswrit
ten:%d\
n",
count
);
}

Pr
ogr
am 3:

#incl
ude<unistd.
h>
i
ntmai n()
{
writ
e(1,"
hell
o\n",
60)
;//
thebyt
est
o bepr
int
ed(
thi
rd par
amet
er)ar
emor
ethant
hedat
a
specif
iedin2ndparameter
}

Pr
ogr
am4:

#i
nclude<unistd.
h>
i
ntmai n()
{
wri
te(1,
"hell
o\n",
3);
//t
heby
test
obepr
int
ed(
thi
rdpar
amet
er)ar
elesst
hant
hedat
aspeci
fi
ed
i
n2ndpar amet er
}

Pr
ogr
am5:

#incl
ude<unistd.h>
#incl
ude<stdio.h>
i
ntmai n()
{
i
ntcount ;
count=writ
e(3,"
hell
o\n",
6);/
/thefil
edescr
ipt
ori
snotoneoft
hepr
e-speci
fi
edonesi
.e.
,0,
1or
2
print
f("
Totalbyteswrit
ten:%d\n"
,count
);
}

Pr
ogr
am 6:
Tor
eaddat
afr
om t
hest
andar
dinputdev
iceandwr
it
eitont
hescr
een

/
/read.
c
#incl
ude<unist
d.h>
i
ntmai n()
{
charbuff[
20];
read(
0,buff
,10)
;/
/read10bytesfr
om standar
dinputdevi
ce(keyboar
d),
stor
einbuf
fer(
buf
f)
writ
e(1,
buff,
10);
//pr
int10by
t esf
rom t
hebufferonthescreen
}

Progr
am 7:
Tor
eaddat
afr
om t
hest
andar
dinputdev
iceandwr
it
eitont
hescr
een
//
read.
c

#incl
ude<uni std.
h>
i
ntmai n()
{
i
ntnr ead;
charbuf f[20];
nread=r ead(0,buff
,10);
//r
ead10byt
esfrom st
andardinputdev
ice(
key
boar
d),st
orei
nbuf
fer
(buff
)
writ
e( 1,
buf f
,nread);
//pr
int10by
tesf
rom t
hebufferont
hescreen
}

Pr
ogram 1:Writ
eapr ogr
am usi
ngopen()syst
em cal
ltor
eadt
hef
ir
st10char
act
ersofan
exi
sti
ngf
ile“
test
.txt
”andpri
ntt
hem onscr
een.

//open. c
#include<st dio.h>
#include<uni std.h>
#include<sy s/types.h>
#include<sy s/st at.
h>
#include<f cntl.
h>
i
ntmai n()
{
i
ntn, fd;
charbuf f
[50];
fd=open( "test.t
xt "
,O_RDONLY) ;/
/openstest.
txti
nr eadmodeandthefil
edescr i
ptori
ssav ed
i
ni ntegerf d.
printf(
"Thef il
edescr i
ptorofthefi
lei
s:%d\n,f
d);//theval
ueoft
hefi
ledescri
ptorispri
nted.
n=r ead(fd,
buf f,
10) ;
//r
ead10char acter
sfrom thefil
epoint
edtobyfi
ledescri
ptorfdandsav e
them i nbuf f
er( buff)
write(1,buff,
n);// wri
teont hescr
eenf r
om thebuffer
}

Progr
am2:Tor
ead10char
act
ersf
rom f
il
e“t
est
.t
xt”andwr
it
ethem i
ntonon-
exi
sti
ngf
il
e
“t
owri
te.
txt

//open2.
c
#incl
ude<unistd.h>
#incl
ude<sys/types.h>
#incl
ude<sys/stat.
h>
#incl
ude<fcntl
.h>
i
ntmai n()
{
i
ntn,fd,
fd1;
charbuff[
50];
fd=open("test.
txt",
O_RDONLY)
;
n=read(fd,buff
,10);
fd1=open( "t
owr i
te.
txt
",
O_WRONLY|
O_CREAT,
0642)
;/
/use t
he pi
pe sy
mbol(
|)t
o separ
ate
O_WRONLYandO_ CREAT
writ
e(fd1,buff,
n);
}

Pr
ogram1:Progr
am usi
nglseek(
)syst
em cal
lthatreads10charact
ersf
rom f
il
e“seeki
ng”and
pr
intonscr
een.Agai
nread10charact
ersandwr i
teonscreen.

#incl
ude<uni std.h>
#incl
ude<f cntl
.h>
#incl
ude<sy s/types.h
#incl
ude<sy s/stat.h>
#intmai n()
{
i
ntn,f;
charbuf f[
10];
f=open("seeking",O_RDWR)
;
read(f
,buff,
10);
writ
e(1,buff,
10);
read(f
,buff,
10);
writ
e(1,buff,
10);
}

Pr
ogram2:Progr
am usi
nglseek(
)syst
em cal
lthatreads10character
sfr
om f
il
e“seeki
ng”and
pr
intonscr
een.Ski
pnext5charact
ersandagainread10character
sandwri
teonscreen.

#incl
ude<uni std.h>
#incl
ude<f cntl
.h>
#incl
ude<sy s/types.h
#incl
ude<sy s/stat.h>
i
ntmai n()
{
i
ntn,f;
charbuf f
[10];
f=open("seeking",O_RDWR);
read(f
,buff,
10);
writ
e(1,buff,
10);
l
seek(f,5,
SEEK_ CUR) ;/
/ski
ps5char
act
ersf
rom t
hecur
rentposi
ti
on
read(f
,buff,
10);
writ
e(1,buff,
10);
}

Program3:Wr
it
eapr
ogr
am t
opr
int10char
act
ersst
art
ingf
rom t
he10t
hchar
act
erf
rom af
il
e
“seeki
ng”.

/
/Letthecontent
soft hef i
l
eF1be“ 1234567890abcdef
ghi
j
xxx
xxxxx”
.Thi
smeanswewant
t
heoutputt
obe“ abcdefghi
j”.
/
/Note:t
hefi
rstcharact
er‘1’i
sat0t
hpositi
on

#i
ncl
ude<unistd.h>
#i
ncl
ude<fcntl.
h>
#i
ncl
ude<sys/types.h
#i
ncl
ude<sys/st at
.h>
#i
ncl
ude<stdio.h>
i
ntmai n()
{
i
ntn, f
,f1;
charbuf f
[10];
f=open( "seeking"
,O_
RDWR);
f1=lseek( f
,10,
SEEK_SET)
;
printf
("Pointerisat%dposi
ti
on\
n",
f1)
;
read(f,buff,
10);
write(1,buff,
10);
}

Program 1:Progr am fordup()syst


em cal
linCt
odupl
i
cat
eaf
il
edescr
ipt
or.
//dup.c
#incl
ude<unistd.h>
#incl
ude<stdio.h>
3i
nclude<fcntl
.h>
i
ntmai n()
{
i
ntold_fd,new_ fd;
ol
d_ f
d=open("test .
txt
",
O_ RDWR);
print
f("
Fil
edescr iptoris%d\n",
old_
fd);
new_ f
d=dup(old_ fd);
print
f("
Newf i
ledescr i
ptori
s%d\ n"
,new_f
d);
}

Program 2:Progr am tousedup2()syst


em cal
li
nli
nuxt
odupl
i
cat
eaf
il
edescr
ipt
or.
//dup2.c
#incl
ude<unistd.h>
#incl
ude<stdio.h>
3i
nclude<fcntl
.h>
i
ntmai n()
{
i
ntold_fd,new_ fd;
ol
d_ f
d=open("test .
txt
",
O_ RDWR);
print
f("
Fil
edescr iptori
s%d\ n"
,ol
d_f
d);
new_ f
d=dup2( old_fd,
7);
print
f("
Newf i
ledescr i
ptori
s%d\n",
new_fd)
;
}

Program 3:Pr ogr am toshowt hatbothfi


ledescript
orpoi
nttot hesamefi
leandsamepoint
er
positionismai ntained
//createaf i
letest .
txtwiththecontent"1234567890abcdefghij
54321"
#include<unistd.h>
#include<stdio.h>
#include<fcntl.
h>
i
ntmai n()
{
i
ntol d_fd,new_ fd;
charbuf f[
10];
old_fd=open("test.txt"
,O_RDWR) ;
read(old_fd,
buff,10);//
readf i
rst10charact
ersusingoldfi
ledescript
or
wr i
te(1,
buff,
10) ;
//printsthem onscreen
new_ fd=dup(old_ f
d) ;
//dupli
catesfi
ledescri
ptor
read(old_fd,
buff,10);//
thisreadwi l
lreadthenex t10character
sev eni
fnewf i
l
edescr
ipt
oris
used
wr i
te(1,
buff,
10) ;
}

Progr am f orfork()system call


#incl ude<stdio.h>
#incl ude<unistd.h>
#incl ude<sys/types.h>
i
ntmai n()
{
pi
d_ tp;
printf("beforefork\n")
;
p=f ork();
i
f(p==0)
{
printf("Iam chil
dhav i
ngid%d\ n",get
pid(
));
printf("Mypar ent'sidis%d\ n",
getppi
d())
;
}
el
se{
printf("Mychi l
d'sidis%d\ n",p)
;
printf("Iam parenthav ingid%d\ n",
getpi
d()
);
}
printf("Common\ n");
}

Progr am f orwai t
()system callwhichmakest hepar
entpr
ocesswai
tfort
hechi
l
dtof
ini
sh.
#incl ude<unistd.h>
#incl ude<sys/types.h>
#incl ude<stdio.h>
#incl ude<sys/wai t.
h>
i
ntmai n()
{
pi
d_ tp;
printf("beforefork\n")
;
p=f ork();
i
f(p==0) //
child
{
printf("Iam chil
dhav i
ngid%d\ n",get
pid(
));
printf("Mypar ent'sidis%d\ n",
getppi
d())
;
}
el
se/ /parent
{
wai t(NULL) ;
printf("Mychi l
d'sidis%d\ n",p)
;
printf("Iam parenthav ingid%d\ n",
getpi
d()
);
}
printf("Common\ n");
}

Pr
ogr
am 2:
Progr
am t
ocr
eat
eanor
phanpr
ocess

#i
ncl
ude<stdio.h
#i
ncl
ude<unistd.h>
#i
ncl
ude<sys/types.h>
i
ntmain(
)
{
pi
d_tp;
p=f
ork(
);

i
f(
p==0)
{
sl
eep(5);/
/childgoestosleepandi nthemeant i
mepar
entt
ermi
nat
es
pr
int
f("Iam chil
dhav i
ngPID%d\ n",
getpid(
));
pr
int
f("Mypar entPIDis%d\n",
getppid()
);
}
el
se
{
pr
int
f("Iam parenthavi
ngPID%d\ n",getpi
d()
);
pr
int
f("MychildPIDis%d\n",p)
;
}
}

//zombi e.c
#include<stdio.h>
#include<unistd.h>
i
ntmai n()
{
pid_tt;
t=fork(
) ;
i
f(t==0)
{
print
f("Chil
dhav i
ngid%d\n",get
pid()
);
}
else
{
print
f("Parenthav i
ngid%d\ n",
getpi
d())
;
sleep(15);//Par entsl
eeps.Runt hepscommanddur
ingt
hist
ime
}
}

//
execl.c
#i
nclude<stdio.h>
#i
nclude<unistd.h>
i
ntmai n()
{
pr
intf
("Beforeex ecl
\n");
execl
("
/ bi
n/ps",
"ps",
"-a"
,NULL)
;/
/
pr
intf
("Aft
erex eclp\
n" )
;
}

//thr
eads
#incl
ude<pt
hread.h>
i
ntpt hr
ead_
create(pt
hread_
t*t
hread,constpt
hread_
att
r_t*
att
r,
voi
d*(
*st
art
_rout
ine)(
voi
d*)
,
voidarg)
;

Program 1:Pr ogr


am t
ocr
eat
ethr
eadsi
nli
nux
.Thr
eadpr
int
s0-
4whi
l
ethemai
npr
ocess
print
s20- 24
#include<stdio.
h>
#include<stdli
b.h>
#incl
ude<unistd.
h>
#incl
ude<pthread.h>
void*t
hread_function(
voi
d* ar
g);
i
nti,
j;
i
ntmai n(
){
pthr
ead_ta_ t
hread; //t
hreaddecl
arat
ion

pthread_ creat e(&a_thread,NULL,t


hread_f
uncti
on,NULL) ;
//threadi scr eated
pthread_ join(a_thread,NULL) ;/
/processwait
sf orthreadtofi
nish./
/Commentt
hisl
i
net
o
seet hedi fference
printf("I
nsi deMai nPr ogram\n")
;
for(j=20; j
<25; j++)
{
printf("%d\ n" ,
j);
sleep( 1);
}
}
void* thread_ function(void*ar
g){
//thewor kt obedonebyt het
hreadisdefi
nedinthisfuncti
on
printf("I
nsi deThr ead\n");
for(i=0;i<5;i++)
{
printf("%d\ n" ,
i);
sleep( 1);
}
}

Program 2:Pr ogr am t ocr eateat hr


ead.Thet hr
eadpri
ntsnumbersfr
om zer
oton,where
valueofni spassedf rom themai nprocesst othethr
ead.Themai
nprocessal
sowai
tsf
orthe
threadt of i
ni shf i
rstandt henpr i
ntsfr
om 20- 24.
#include<st di o.h>
#include<st dl i
b. h>
#include<uni std. h>
#include<pt hread. h>
#include<st r i
ng. h>
void* thread_ funct ion(void* arg);
inti,
n,j;
intmai n(){
char* m=" 5" ;
pthread_ ta_ thread; / /threaddecl arati
on
void* resul t;
pthread_ cr eat e(&a_ t
hread, NULL, thr
ead_ f
uncti
on,m);/
/thr
eadi
screat
ed
pthread_ join( a_ thread, &result);
printf("Thr eadj oi ned\n");
for(j
=20; j
<25; j++)
{
printf("%d\ n",j);
sleep( 1);
}
printf("threadr etur ned%s\ n",
(char*)resul
t)
;
}
void* thr ead_ funct ion(void* arg){
intsum=0;
n=at oi(arg) ;
for(i
=0; i
<n; i++)
{
pr
int
f("%d\n"
,i
);
sl
eep(1);
}
pt
hread_exit
("
Done"
);/
/Thr
eadr
etur
ns"
Done"
}

Progr am 3:Pr ogram t ocr eateat hread.Thet hreadi spassedmoret hanoneinputf


rom the
mai npr ocess.Forpassi ngmul ti
plei nputsweneedt ocreatestr
uctureandincl
udeallthe
variablest hatar etobepassedi nthisstructur
e.
#include<st dio.h
#include<pt hread.h>
structar g_ struct{ / /structurewhi chcont ai
nsmul tipl
evariabl
esthatar
etopassedasinput
tot het hr ead
intar g1;
intar g2;
};
void* ar gument s(void*argument s)
{
structar g_ str
uct* args=ar gument s;
print f("%d\ n",args->ar g1);
print f("%d\ n",args->ar g2);
pthr ead_ exi t
(NULL) ;
}
i
ntmai n()
{
pt hread_ tt;
st ructar g_structargs;
ar gs. arg1=5;
ar gs. arg2=7;
pt hread_ create(&t,NULL, argument s,&args);
//struct ur epassedas4t har gument
pt hread_ joi
n(t,NULL) ;/*Wai tuntilt
hreadisf i
nished*/
}

//deadlock
#include<stdi o.h>
#include<pt hread. h>
#include<uni std.h>
void* f
unct i
on1( );
void* f
unct i
on2( );
pthread_mut ex_ tfir
st_mutex;//mut exlock
pthread_mut ex_ tsecond_ mutex;
i
ntmai n(){
pthread_mut ex_ i
nit(&fi
rst_
mut ex,
NULL) ;//
ini
ti
ali
zethelock
pthread_mut ex_ i
nit(&second_mut ex,NULL);
pthread_tone, two;
pthread_creat e(&one, NULL,f
unct i
on1, NULL);/
/createthr
ead
pthread_creat e(&t wo, NULL,f
unct i
on2, NULL);
pthread_join(one, NULL) ;
pthread_join(two, NULL) ;
print
f("Threadj oi ned\n");
}
void* f
unct i
on1(){
pthread_mut ex_ l
ock( &fi
rst
_mut ex);//t
oacquiretheresour
ce/mut
exl
ock
pri
ntf("Thr
eadONEacqui redf i
rst_mutex \
n");
sl
eep( 1);
pthread_mutex_l
ock(&second_ mut ex);
pri
ntf("Thr
eadONEacqui redsecond_ mutex \
n");
pthread_mutex_unl
ock(&second_ mutex);//torel
easet
her
esour
ce
pri
ntf("Thr
eadONEr eleasedsecond_ mutex \
n")
;
pthread_mutex_unl
ock(&first
_mut ex);
pri
ntf("Thr
eadONEr eleasedf i
rst_mutex\n");
}
void*functi
on2(){
pthread_mutex_l
ock(&second_ mut ex);
pri
ntf("Thr
eadTWOacqui redsecond_ mut ex\n"
);
sl
eep( 1);
pthread_mutex_l
ock(&fi
rst_mut ex);
pri
ntf("Thr
eadTWOacqui redfirst_mutex\n")
;
pthread_mutex_unl
ock(&first
_mut ex);
pri
ntf("Thr
eadTWOr eleasedf ir
st_mut ex\n")
;
pthread_mutex_unl
ock(&second_ mutex);
pri
ntf("Thr
eadTWOr eleasedsecond_ mut ex\n"
);
}

//racecondi t i
on
#include<pt hread. h>
#include<st dio. h>
#include<uni st d.h>
void* fun1( );
void* fun2( );
i
ntshar ed=1; / /sharedv ari
abl e
i
ntmai n( )
{
pthread_ tt hread1, thread2;
pthread_ creat e(&thr ead1, NULL, fun1, NULL) ;
pthread_ creat e(&thr ead2, NULL, fun2, NULL) ;
pthread_ join( thread1, NULL) ;
pthread_ join( thread2, NULL) ;
printf(
"Fi nalv alueofshar ed i s%d\ n",
shared);/ /
printsthelastupdat
ed v
alueofshar
ed
variable
}
void* fun1( )
{
i
ntx ;
x=shar ed; // threadoner eadsv alueofshar edv ar
iable
printf(
"Thr ead1r eadst hev alueofshar edv ar
iabl
eas%d\ n"
,x)
;
x++; //thr eadonei ncrement si tsv alue
printf(
"Local updat ionbyThr ead1: %d\ n"
,x);
sleep(1) ;/ /thr eadonei spr eempt edbyt hr
ead2
shar ed=x; //thr eadoneupdat est hev alueofshar edv ari
abl
e
printf(
"Val ueofshar edv ar
iabl eupdat edbyThr ead1is: %d\
n",
shared)
;
}
void* fun2( )
{
i
nty ;
y=shar ed; // t
hr eadt wor eadsv al
ueofshar edv ar
iable
printf(
"Thr ead2r eadst hev alueas%d\ n"
,y
) ;
y--;//t
hr eadt woi ncr ement sitsv alue
printf(
"Local updat ionbyThr ead2: %d\ n"
,y);
sl
eep(1);/
/threadtwoispreemptedbythr
ead1
shared=y;
//threadoneupdatestheval
ueofsharedv
ari
abl
e
pri
ntf(
"Val
ueofshar edvar
iableupdat
edbyThread2i
s:%d\
n",
shar
ed)
;
}

//nodeadl ock&r acecondi t i


on
#include<pt hread. h>
#include<st dio. h>
#include<uni st d.h>
void* fun1( );
void* fun2( );
i
ntshar ed=1; / /shar edv ariabl e
pthread_ mut ex _ tl;//mut exl ock
i
ntmai n( )
{
pthread_ mut ex _ i
nit(&l ,NULL) ;//initial
iz i
ngmut exlocks
pthread_ tt hread1, thread2;
pthread_ creat e(&t hread1, NULL, f un1, NULL) ;
pthread_ creat e(&t hread2, NULL, f un2, NULL) ;
pthread_ join( thread1, NULL) ;
pthread_ join( thread2, NULL) ;
printf(
"Fi nalv alueofshar ed i s%d\ n",
shar ed) ;/ /
printsthel astupdat
ed val
ueofshared
variable
}
void* fun1( )
{
i
ntx ;
printf(
"Thr ead1t ryingt oacqui relock\ n");
pthread_ mut ex _ l
ock( &l);// thr eadoneacqui rest hel ock.Now t hr
ead2willnotbeabl
et o
acqui ret hel ock/ /unt ilitisunl ockedbyt hread1
printf(
"Thr ead1acqui redl ock\ n");
x=shar ed; // threadoner eadsv alueofshar edv ariable
printf(
"Thr ead1r eadst hev al ueofshar edv ariableas%d\ n"
,x)
;
x++; //thr eadonei ncr ement si tsv alue
printf(
"Local updat i
onbyThr ead1: %d\ n",
x);
sleep(1) ;/ /thr eadonei spr e
shar ed=x; //thr eadoneupdat est hev alueofshar edv ari
able
printf(
"Val ueofshar edv ari
abl eupdat edbyThr ead1i s: %d\n",
shared)
;
pthread_ mut ex _ unlock( &l);
printf(
"Thr ead1r eleasedt hel ock\ n" );
}
void* fun2( )
{
i
nty ;
printf(
"Thr ead2t ryingt oacqui relock\ n");
pthread_ mut ex _ l
ock( &l);
printf(
"Thr ead2acqui redl ock\ n");
y=shar ed; // t
hr eadt wor eadsv alueofshar edv ari
abl e
printf(
"Thr ead2r eadst hev al ueas%d\ n",
y);
y--;//t
hr eadt woi ncr ement si tsv alue
printf(
"Local updat i
onbyThr ead2: %d\ n",
y);
sleep(1) ;/ /thr eadt woi spr eempt edbyt hread1
shar ed=y ; //thr eadoneupdat est hev alueofshar edv ari
able
printf(
"Val ueofshar edv ari
abl eupdat edbyThr ead2i s: %d\n",
shared)
;
pthread_ mut ex _ unlock( &l);
printf(
"Thr ead2r eleasedt hel ock\ n" );
}

//semaphor e
#include<pt hread. h>
#include<st dio.h>
#include<semaphor e.h>
#include<uni std. h>
void* fun1( );
void* fun2( );
i
ntshar ed=1; //shar edv ar i
abl e
sem_ ts; // semaphor ev ariable
i
ntmai n()
{
sem_ i
ni t(
&s, 0,1) ;/ /initi
alizesemaphor ev ariable-1star gumentisaddressofv ar
iabl
e,2ndis
numberofpr ocessesshar i
ngsemaphor e,3r dar gumentist heini
ti
alv al
ueofsemaphor e
variable
pthread_ tt hread1, thread2;
pthread_ creat e( &t hread1, NULL, fun1,NULL) ;
pthread_ creat e( &t hread2, NULL, fun2,NULL) ;
pthread_ join( t
hr ead1, NULL) ;
pthread_ join( t
hr ead2, NULL) ;
printf("Finalv al ueofshar ed i s%d\ n",
shar ed);/ /
pri
ntsthel astupdated val
ueofshar ed
variable
}
void* fun1( )
{
i
ntx ;
sem_ wai t(&s) ;/ /execut eswai toper ati
onons
x=shar ed;// thread1r eadsv alueofshar edv ariable
printf("Thr ead1r eadst hev al
ueas%d\ n"
,x);
x++; //thr ead1i ncr ement sitsv al
ue
printf("Local updat i
onbyThr ead1: %d\ n"
,x);
sleep( 1) ;
/ /thread1i spr eempt edbyt hread2
shar ed=x; //thr eadoneupdat est hev alueo
printf("Val ueofshar edv ariableupdat edbyThr ead1is:%d\n"
,shared)
;
sem_ post (&s) ;
}
void* fun2( )
{
i
nty ;
sem_ wai t(&s) ;
y=shar ed; // t
hr ead2r eadsv alueofshar edv ariable
printf("Thr ead2r eadst hev al
ueas%d\ n"
,y
) ;
y--;//t
hr ead2i ncr ement si t
sv alue
printf("Local updat i
onbyThr ead2: %d\ n"
,y);
sleep( 1) ;
/ /thread2i spr eempt edbyt hread1
shar ed=y ; //thread2updat est hev alueofshar edv ari
abl
e
printf("Val ueofshar edv ariableupdat edbyThr ead2is:%d\n"
,shared)
;
sem_ post (&s) ;
}

//
dini
ngphilosopherpr
obl
em
#i
nclude<st
dio.h>
#i
nclude<st
dlib.
h>
#i
nclude<pt
hread.h>
#include<semaphor e.h>
#include<uni st d.h>
sem_ tchopst ick[5];
void*phi l
os(v oid* )
;
voideat (i
nt);
i
ntmai n()
{
i
nti ,
n[5];
pthread_ tT[5];
for(i
=0;i<5;i
++)
sem_ init(
&chopst i
ck[i
],0,1);
for(i
=0;i<5;i
++) {
n[i]
=i;
pthread_ create( &T[i
],NULL, phil
os,(void* )&n[i
]);
}
for(i
=0;i<5;i
++)
pthread_ j
oin(T[ i]
,NULL) ;
}
void*phi l
os(v oid*n)
{
i
ntph=* (i
nt* )n;
printf
("Philosopher%dwant stoeat \n",ph);
printf
("Philosopher%dt ri
estopi ckl eftchopst i
ck\n",ph);
sem_ wai t(
&chopst i
ck[ph] )
;
printf
("Philosopher%dpi cksthel eftchopst ick\n",
ph) ;
printf
("Philosopher%dt ri
estopi ckt her ightchopstick\n",
ph)
;
sem_ wai t(
&chopst i
ck[(ph+1) %5]);
printf
("Philosopher%dpi cksther ightchopst i
ck\n",
ph) ;
eat(ph);
sleep(2);
printf
("Philosopher%dhasf i
nishedeat ing\n",
ph);
sem_ post (&chopst i
ck[ (ph+1)%5]);
printf
("Philosopher%dl eavesther ightchopst i
ck\n",
ph) ;
sem_ post (&chopst i
ck[ ph])
;
printf
("Philosopher%dl eavesthel eftchopst ick\n",
ph);
}
voideat (i
ntph)
{
printf
("Philosopher%dbegi nst oeat \n",
ph) ;
}

//
IPC-int
erprocesscommunicat
ion
#i
nclude<stdi
o.h>
FI
LE* popen(constchar*
command,constchar*
type)

#incl
ude<stdio. h>
#incl
ude<stdlib.h>
#incl
ude<unist d.h>
#incl
ude<string. h>
i
ntmai n()
{
FILE*rd;
charbuf f
er[
50] ;
spri
ntf(buff
er,"
namef i
rst
");
rd=popen("wc- c",
"w"
);//wc- c-
>istheprocesswhichcountsthenumberofchar
act
ers
passed.2ndpar amet
eris"w"whi
chmeanspi
peisopenedi
nwr i
ti
ngmode
fwr
it
e(buff
er,
si
zeof
(char
),
str
len(
buf
fer
),
rd)
;//t
owr
it
ethedat
aint
othepi
pe
pcl
ose(r
d);
}

Pr ogram t oreadf rom apipei.e.t


orecei
vedat
afrom anot
herpr
ocess
#incl ude<stdio.h>
#incl ude<stdli
b.h>
#incl ude<unistd.h>
#incl ude<stri
ng. h>
i
ntmai n()
{
FILE* rd;
charbuf fer[
50];
rd=popen( "l
s",
"r");
//pipeopenedinreadi
ngmode
fread( buffer
,1, 40,rd);/
/wil
lreadonly50char
act
ers
printf("%s\n",buf f
er);
pcl ose( r
d);
}

Pr
ogram f
orIPCusi ngnamedpipes(
mkfi
fo(
))
#i
ncl
ude<sys/ty
pes.h>
#i
ncl
ude<sys/stat
.h>
i
ntmkfi
fo(constchar*pat
hname,mode_
tmode);

Program1: Creatingf i
fo/
namedpi pe
#include<stdi
o.h>
#include<sys/ty
pes. h>
#include<sys/stat.
h>
i
ntmai n()
{
i
ntr es;
res=mkf i
fo("
fif
o1",0777);/
/creat
esanamedpi
pewi
tht
henamef
if
o1
printf
("namedpi pecr eat
ed\n"
);
}

Program2: Writ
ingtoaf i
fo/
namedpipe(2.
c)
#include<unistd.h>
#include<stdio.h>
#include<fcntl.
h>
i
ntmai n()
{
i
ntr es,
n;
res=open( "
fif
o1" ,
O_WRONLY) ;
write(r
es,"Message" ,
7);
printf
("SenderPr ocess%dsentthedat
a\n"
,get
pid(
));
}

Program 3: Readi ngf


rom t
henamedpi
pe(3.
c)
#include<unistd.h>
#include<stdio.h>
#include<fcntl.
h>
i
ntmai n(
)
{
i
ntr es,
n;
charbuf f
er[100] ;
res=open( "
fif
o1",
O_ RDONLY);
n=r ead(r
es,buff
er,
100);
printf(
"Readerprocess%dst ar
ted\
n",
getpi
d()
);
printf(
"Datareceiv
edbyr ecei
ver%dis:
%s\n",
getpi
d()
,buf
fer
);
}

Thisprogr
am cr
eatesashar
edmemor ysegment
,at
tachesi
tsel
ftoi
tandt
henwr
it
essome
contenti
ntot
hesharedmemorysegment
.

#include<stdi o.h>
#include<stdl i
b.h>
#include<uni std.h>
#include<sy s/shm. h>
#include<string. h>
i
ntmai n()
{
i
nti ;
void* shared_ memor y
;
charbuf f[
100] ;
i
ntshmi d;
shmi d=shmget (
(key _t
)2345, 1024, 0666| I
PC_ CREAT);//cr
eatessharedmemor ysegmentwith
key2345, hav ingsi ze1024by t
es.IPC_ CREATi susedt ocreatet
hesharedsegmenti fi
tdoes
notexi st
.0666ar et hepermi sionsont heshar edsegment
printf
("Keyofshar edmemor yi s%d\ n",shmid);
shared_ memor y=shmat (shmi d,NULL,0) ;
//processattachedtosharedmemor ysegment
printf
("Process at tached at%p\ n",
shar ed_
memor y);//t
his pri
ntsthe address wher
et he
segmenti sat tachedwi t
ht hi
spr ocess
printf
("Entersomedat atowr itetoshar edmemor y\n")
;
read(0,buff,
100) ;//getsomei nputf r
om user
strcpy(shared_ memor y,
buff)
; //datawr it
tentoshar edmemor y
printf
("Youwr ote: %s\ n",
(char* )shared_memor y)
;
}

Thispr
ogr
am att
achesit
selftot
hesharedmemor
ysegmentcr
eat
edi
nPr
ogr
am 1.Fi
nal
l
y,i
t
readst
hecont
entofthesharedmemory

#include<stdi o.h>
#include<stdl i
b.h>
#include<uni std.h>
#include<sy s/shm. h>
#include<string. h>
i
ntmai n()
{
i
nti ;
void* shared_ memor y;
charbuf f[
100] ;
i
ntshmi d;
shmi d=shmget ((key _
t)2345,1024,0666);
print
f("Keyofshar edmemor yis%d\n",
shmid);
shared_ memor y =shmat (shmid,
NULL,0);/
/processattachedtoshar
edmemor
ysegment
print
f("Processat tachedat%p\ n",
shared_memor y)
;
print
f("Datar eadf rom shar edmemor yis:%s\n",
(char*)shar
ed_memor
y);
}

Pr
ogr
am f
orI
PCusi
ngmessagequeues
i
ntmsgget(
key _
tkey,i
ntmsgf l
g);
i
ntmsgsnd(intmsqid,constv
oid*msg_ pt
r,si
ze_
tmsg_ sz,i
ntmsgfl
g);
i
ntmsgrcv
(intmsqid,void*msg_ptr
,si
ze_tmsg_sz,l
ongintmsgtype,i
ntmsgf
lg)
;
i
ntmsgctl
(i
ntmsqid, i
ntcommand, str
uctmsqid_ds*buf)
;

CommandDescr i
ption
I
PC_STATSetst hedat ai
nthemsqid_dsst
ruct
uretoref
lectthev al
uesassoci
atedwi
tht
he
messagequeue.
I
PC_SETIfthepr ocesshaspermi
ssiontodoso,thissetst hevaluesassoci
atedwi
tht
he
messagequeuetot hosepr
ovi
dedi
nt hemsqi
d_dsdat
astructure.
I
PC_RMIDDeletesthemessagequeue.

Program 1: Pr ogr am forI PCusingMessageQueuesTosenddat atoamessagequeue


#include<st dlib.h>
#include<st dio. h>
#include<st ring. h>
#include<uni st d.h>
#include<sy s/ types. h>
#include<sy s/ ipc.h>
#include<sy s/ msg. h>
#def i
neMAX_ TEXT512/ /maximum lengthoft
hemessagethatcanbesental
l
owed
structmy _ msg{
l
ongi ntmsg_ type;
charsome_ tex t[MAX_ TEXT] ;
};
i
ntmai n()
{
i
ntr unning=1;
i
ntmsgi d;
structmy _ msgsome_ data;
charbuf fer[50] ;/ /
arrayt ostoreuseri
nput
msgi d=msgget ((key _t
)14534,0666|I
PC_ CREAT)
;
i
f( msgi d==- 1)/ /-1meanst hemessagequeuei snotcr
eat
ed
{
printf
("Errorincr eat i
ngqueue\ n")
;
exit(
0);
}

whi l
e(running)
{
pri
nt f
("Entersomet ext:
\n");
fgets(buffer,50,
stdin);
some_ data.msg_ type=1;
strcpy(some_ data.
some_ text
,buf
fer
);
i
f(msgsnd( msgi d,(
voi d*)&some_d
MAX_ TEXT, 0)==-1)/ /msgsndr etur
ns-1i
fthemessagei
snotsent
{
pri
nt f
("Msgnotsent \n")
;
}
i
f(strncmp( buf f
er,"
end" ,
3)==0)
{
running=0;
}
}
}
Progr am 2:Pr ogr am f orIPCusingMessageQueuesTor ecei
ve/
readmessagef
rom t
heabov
e
-createdmessagequeue
#include<stdl i
b. h>
#include<stdi o.h>
#include<string. h>
#include<uni std. h>
#include<sy s/t ypes. h>
#include<sy s/ipc. h>
#include<sy s/msg. h>
structmy _msg{
l
ongi ntmsg_ type;
charsome_ tex t[BUFSI Z];
};
i
ntmai n()
{
i
ntr unning=1;
i
ntmsgi d;
structmy _msgsome_ data;
l
ongi ntmsg_ to_r ec=0;
msgi d=msgget ((key _t)12345,
0666|I
PC_CREAT);
whi l
e(runni
ng)
{
msgr cv (
msgi d, (voi d*)&some_ dat
a,BUFSIZ,
msg_t
o_ r
ec,
0);
printf
( "
Datar ecei v ed:%s\ n",
some_data.
some_text
);
i
f (
strncmp( some_ data.some_ t
ext
,"
end",
3)==0)
{
running=0;
}
}
msgct l
(msgi d,IPC_ RMI D,0)
;
}

You might also like