Вы находитесь на странице: 1из 30

System Programming (part -2)

sriram.popuri@sun.com

Agenda

Signals Locking Mechanisms Daemons Shell mplementation

Signals

Signals are so!t"are interrupts# they pro$ide a "ay o! handling asynchronous e$ents %ach signal has a name "hich starts "ith &S '(

e.g) S '* LL# S ' +,# S 'S%'-

.hen signal occurs# one o! the !ollo"ing actions can /e taken.


gnore the signal De!ault action (usually terminates the process) 0andle the signal

Signals
Signal name SIGABRT SIGALRM SIGCHLD SIGINT SIG !IT SIG$ILL SIGT(RM SIGST)* SIGTST* SIGC)NT SIG!SR+ SIG!SRSIG*I*( Description abnormal termination, generated by abort() time out "timer set &/ alarm()# Default action terminate (core dump) terminate change in status of child process ignore terminal interrupt "pressing CTRL-C # terminate terminal 0uit "pressing CTRL-\ # terminate "core dump# terminate "%ill# process "cannot &e caught'ignored# terminate terminate process terminate stop process "cannot &e caught'ignored# stop terminal stop "pressing CTRL-Z # stop continue stopped process continue user,defined signal terminate user,defined signal terminate .rite to pipe .ith no readers terminate

Sending Signals
int kill(pid_t pid, int signo) int raise(int signo) void abort(void)

abort sends a SIGABRT signal to itsel!# it does not return i! the signal is caught# abort() still doesn1t return2 raise sends the signal signo to itsel! kill sends the signal signo to the speci!ied process) superuser can send signals to any process other"ise real 3 D o! sender must match real 3 D o! recei$er .e can also send signals !rom the controlling terminal o! the process (normally the terminal used /y the shell).

Signal 0andler 4unction


3se the signal() to register the signal handler !unction. signal() registers a ne" signal handler !unction and returns the pre$ious signal handler !unction Prede!ined actions

S '5%66 S '5D4L S '5 '+


typede! $oid sigptr(int)7 sigptr 8signal(int signo# sigptr 8handler)7

%9ample
static int signal_flag = 0; void sig_int(int signo) { if (signal(SIGINT, sig_int)== SIG_ERR){/*re-establish*/ perror("Cannot catch SIGINT");exit(1);} printf("Received signal %d\n", signo); signal_flag = 1; } int main(void) { if (signal(SIGINT, sig_int) == SIG_ERR) { perror("Cannot catch SIGINT"); exit(1); } while(!signal_flag) pause(); printf("Received SIGINT\n"); return 0; }

psig(:M)

List the signal action and handlers !or each signals.


/ash-;.<<= psig >pgrep automountd> :<?@) AusrAli/Aauto!sAautomountd 03P caught "arn5hup 6%S%,0A+D#+BD%4%6 +, de!ault C3 , de!ault ... ...

3nrelia/le Signals

,here "ere !e" pro/lems "ith signals in earlier $ersions o! 3ni9. %arlier $ersions o! 3ni9 used to reset the signal handler to de!ault action.

,he pro/lem is one must reesta/lish handler !rom the signal handler itsel!. ! signal occurs again /e!ore reesta/lishing handler then de!ault action takes place. De!ault action usually is to terminate the process.

3nrelia/le Signals (contd...)


Dinclude Esignal.hF sigcatcher() G print!(&P D Hd caught oneIn(#getpid())7 signal(S ' +,# sigcatcher)7 J main() G int ppid7 signal(S ' +,# sigcatcher)7 A8 setup the handler 8A i! (!ork() KK <) G sleep(@)7 A8 gi$e enough time !or setup 8A ppid K getppid()7 !or(77) i! (kill(ppid# S ' +,) KK -:) e9it()7 J nice(:<)7 A8 lo"er priority# greater chance o! e9hi/iting race 8A !or(77) J

3nrelia/le Signals (contd...)

A signal could get lost i! it occurs at an &une9pected( time.

May cause deadlock


static int signal5!lag K <7 $oid sig5int(int signo) G signal5!lag K :7 J int main($oid) G signal(S ' +,# sig5int)7 "hile(2signal5!lag) pause()7 return <7 J

3nrelia/le Signals

Slo" system calls can /lock a process reading !or a terminal or pipe etc. ,hey may /e interrupted /y a signal. ,hese system calls needs to /e restarted. Async-Signal-sa!e !unctions

.e don1t kno" "here the process is e9ecuting "hen the signal arri$ed. ! "e call some non async-signal-sa!e !unctions !rom signal handler # then things may go "rong. ,here is only one errno $aria/le per process. Signal handler may call !unctions "hich modi!y errno.

6elia/le signals

Modern 3ni9 sol$es most o! these pro/lems. 6elia/le signal terminology


A signal is generated !or a process "hen the e$ent that causes that signal occurs. A signal is delivered to a process "hen its action is taken A signal is pending /et"een the generation and its deli$ery. A process may block the deli$ery o! a signal (using !unction sigprocmask())# it remains pending until the process un/locks it or changes the action to ignore it

6elia/le Signals (contd...)

%ach process has a signal mask


Set o! signals currently /locked !rom deli$ery to the process. Signal mask can /e manipulated /y using signprocmask()

Signals that are /locked or currently pending can /e !ound using sigpending().
int sigprocmask(int ho"# sigset5t 8set# sigset5t 8oset)7 int sigpending(sigset5t 8set)7 int sigsuspend(sigset5t 8sigmask)7

6elia/le Signals (contd...)


,he pre!erred inter!ace !or relia/le signals is sigaction(). Protect critical regions o! code against un"anted signals using sigsuspend().
struct sigaction G $oid (8sa5handler)()7 A8 signal handler 8A sigset5t sa5mask7 A8 additional signal to /lock 8A int sa5!lags7 A8 signal options 8A J int sigaction(int signo# struct sigaction 8act# struct sigaction 8oact)7 int sigaddset(sigset5t 8set# int signo)7

%9ample
http)AAc$s.opensolaris.orgAsourceA9re!AonAusrAsrcAcmdAcmd-inetAusr.s/inAsnoopAsnoop.c :2< :L; :LN :L@ :LL :LP :L? :LS :P< :P: :P2 :P; :PN :P@ :PL :PP struct sigaction sigact7 A8 nitialiMe a master signal handler 8A sigact.sa5handler K +3LL7 sigact.sa5sigaction K snoop5sigreco$er7 ($oid) sigemptyset(Osigact.sa5mask)7 sigact.sa5!lags K SA5B+S,AQ*RSA5S ' +4B7 A8 6egister master signal handler 8A i! (sigaction(S '03P# Osigact# (struct sigaction 8)+3LL) E <) G perror(T.arning) sigactionT)7 e9it(:)7 J i! (sigaction(S ' +,# Osigact# (struct sigaction 8)+3LL) E <) G perror(T.arning) sigactionT)7 e9it(:)7 J

Locking

Locking types

Ad$isory locking Mandatory locking 4ile locking 6ecord locking

Locking granularity

Ad$isory Locking

Doesn1t guarantee e9clusi$e access. A process can ignore a ad$isory lock and "rite to a !ile that is locked. Processes should coordinate !or using these locks.

http)AAc$s.opensolaris.orgAsourceA9re!AonAusrAsrcAli/Ali/cAportAgenAlckp"d!.c
P< lckp"d!($oid) G ?N !lock.l5type K 45.6LQ*7 ?@ i! (!cntl(!ildes# 45S%,L*# O!lock) 2K -:) G ... ::; int ::N ulckp"d!($oid) G ... ::? !lock.l5type K 453+LQ*7 ::S ($oid) !cntl(!ildes# 45S%,L*# O!lock)7

struct !lock !lk7 !lk.l5"hence K S%%*5Q367 !lk.l5start K S%%*5Q367 !lk.l5len K :<<L7

Mandatory locking

%$ery readA"rite reUuest is $eri!ied i! the operation doesn1t inter!ere "ith lock held /y a process. ,o ena/le mandatory locking# turn o!! group e9ecute /it and turn on the mandatory locking !ield.
< Apr :2 <<)2S test < Apr :2 <<)2S test < Apr :2 <<)2S test

/ash-;.<<D ls -l test -r"9r-9r-9 : root root /ash-;.<<D chmod g-9 test /ash-;.<<D ls -l test -r"9r--r-9 : root root /ash-;.<<D chmod Vl test /ash-;.<<D ls -l test -r"9r-lr-9 : root root

Daemons

A Daemon is a process that e9ecutes in /ackground. A daemon "ill /e either "aiting !or a e$ent to occur or per!orm some periodic operation. ,ypically daemons are

Started once "hen system comes up. Li!etime is throughout the system time. Spend most o! the time "aiting. 4reUuently spa"n other processes to handle reUuests.

Daemon process

Qlose all !ile descriptors. Qhange "orking directory. 6eset !ile access creation mask. 6un in /ackground. Diassociate !rom process group and control terminal. gnore terminal AB signals.

http)AAc$s.opensolaris.orgAsourceA9re!AonAusrAsrcAcmdA!s.dAn!sAn!sdAn!sd.c
;P< ;P: ;P2 ;P; ;PN ;P@ ;PL ;PP ;PS ;?< ;?: ;?2 ;?; ;?N ;?@ ;?L ;?P ;?? A8/ackground8A pid K !ork()7 i! (pid E <) G perror(Tn!sd) !orkT)7 e9it(:)7 J i! (pid 2K <) e9it(<)7 A8 8 Qlose e9isting !ile descriptors# open TAde$AnullT as 8 standard input# output# and error# and detach !rom 8 controlling terminal. 8A close!rom(<)7 ($oid) open(TAde$AnullT# B56DB+LW)7 ($oid) open(TAde$AnullT# B5.6B+LW)7 ($oid) dup(:)7 ($oid) setsid()7

A Daemon e9ample

Shell

A shell is a stand-alone program. A command interpreter. A 3ni9 user interacts "ith BS through Shell. A shell has /uilt-in commands and e9ec1s user speci!ied programs.

Shell 4eatures

Program %9ecution 6edirection Pipe Shell Xuilt-in Qommand %n$ironment Management Yo/ Qontrol

ls R more

%9ample

A8 shell program 8A i! (2!ork()) G A8 child su/ shell 8A int p!dZ2[7 A8to hold pipe descriptors8A pipe(p!d)7 i! (2!ork()) G dup2(p!dZ:[# :)7A8 dup "rite end o! pipe to S,DB3, 8A A8 close unused !ds 8A close(<)7 close(p!dZ<[)7 close(p!dZ:[)7 e9ecl(TAusrA/inAlsT# TlsT# +3LL)7A8 e9ec program more 8A J dup2(p!dZ<[# <)7 A8 dup read end o! the pipe to S,D + 8A A8 close unused !ds 8A close(p!dZ:[)7 close(p!dZ<[)7 e9ecl(TAusrA/inAmoreT# TmoreT# +3LL)7A8 e9ec program more 8A J

%9ample \ Yo/ control


ksh=yes y y ... ... ]^Z:[ V Stopped (S 'S,P)

yes

truss -p >pgrep ksh>


statLN(TAusrA/inAyesT# <944X4%?N<) K< sigprocmask(S '5S%,MAS*# <944X4%?D?# <9<<<<<<<<) K < !ork() K 2S?2@ ... "aitid(P5ALL# <# <944X4%@@<# .%_ ,%DR.,6APP%DR.S,BPP%DR.+B0A+') K < sigaction(S 'QLD# <944X4%@:<# <944X4%@S<) K< "rite(2# T Z : [ V S t o p p eT..# ;P) K ;P

%9ample \ Yo/ control (contd...)


... ]^Z:[ V Stopped (S 'S,P) ksh=I!g y y ... yes

truss oAp
read(<# T I ! gInT# :<2N) KN ... sigaction(S 'QLD# <944X4%P2<# <944X4%PA<) K< "aitid(P5ALL# <# <944X4%PL<# .%_ ,%DR.,6APP%DR.S,BPP%D) (sleeping...)

Suggested %9ercises
Bpen a terminal in one "indo" and in another "indo" truss the shell (truss -p Eprocessid o! !irst shellF). B/ser$e the shell implementation. mplement the shell1s `o/ control. mplement shell code to reap the e9it status o! the process. ! you type &=a( at the shell prompt# it "ill gi$e the e9it status o! pre$ious command. denti!y code "hich uses sigaction() in opensolaris source /ase. .rite a daemon program "hich "ill "ake up e$ery ;<secs and log a message (hint)handle S 'AL6M). Also ensure a single instance o! this daemon is running. (hint) use !ile locking techiniUue)

6e!erences
Solaris nternals \ Architecture# tools and techniUues /y Yames Mauro and 6ichard Mc Dougall http)AA""".solarisinternals.comA http)AA""".opensolaris.orgAosA http)AAdocs.sun.comA http)AA""".sun.comA/igadminA Post your Uueries at http)AA!orum.sun.com and the opensolaris discussion aliases

,hank you

Вам также может понравиться