0% found this document useful (0 votes)
9 views15 pages

Module-5 (USP) Notes

USP 5th module notes

Uploaded by

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

Module-5 (USP) Notes

USP 5th module notes

Uploaded by

premkumar74802
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
SIGNALS AND DAEMON PROCESSES jgnals 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. teach | SreBus hardware fault [srecancex ‘abnormal terr ‘timer expired (alarm), threads library internal use ‘change in status of child “continue stopped process arithmetic excepti checkpoint freeze hangup ~~ legal instruction status request from keyboard terminal interrupt character asynchronous /0 hardware fault termination | SIGSTKFLT coprocessor stack fault | SIGsToP | sisys~ threads library internal use write to pipe with no readers ~ pollabie event (p01) ing time alarm (setitimer) ~ power fall/restart terminal quit character invalid memory reference “checkpoint thaw ~~ Hardware fault /sIGrste em ‘terminal stop character background read from control tty terminatetcore terminate terminatercore ignore ignore continue/ignore terminatetcore terminate+core ignore terminate terminate*core ignore terminate terminate/ignore terminate+core terminate ignore terminate terminate terminate terminate/ignore terminatetcore terminatetcore terminate stop process terminate+core terminate ignore terminate+core stop process stop process RNSIT UNIX SYSTEM PROGRAMMING NOTES [ StapT60—packaround wite to control tty stop process | “SIGURG ~~ “Urgent condition (sockets) ignore = : | SIGUSRI user-defined signal terminate 1 [BicusR2 “User-defined ignal terminate 71 | StovrALaN terminate | | SEGHATTENG” threads library internal use ignore | | SIGWINCH “terminal window size change _—_—ignore | HexeeT ibexceeded(setctimit) terminatevcore/ignore | | SIGKFSZ limit exceeded (set rlimit) terminate+core/ignore | SIGKRES ~~ fésource contvol exceeded Ignore Z When a signal is sent to a process, itis pending on the process to handle it. The process can react to pending signals In one of three ways: Accept the default action of the signal, which for most signals will terminate the process. > Ignore the signal. The signal will be discarded and it has no affect whatsoever on the recipient process. > Invoke a user-defined function. The function is known as a signal handler routine and the signal is said to be caught when this function is called. ‘THE UNIX KERNEL SUPPORT OF SIGNALS + Whena signal is generated for a process, the kernel will set the corresponding signal flag in the process table slot of the recipient process. + Ifthe recipient process is asleep, the kernel will awaken the process by scheduling + When the recipient process runs, the kernel will check the process U-area that contains an array of signal handling specifications. * Ifarray entry contains a zero value, the process will accept the default action ofthe signal. + array entry contains a1 value, the process will ignore the signal and kernel will discard it. ‘= If array entry contains any other value, itis used as the function pointer for a user-defined signal handler routine. ‘SIGNAL The function prototype of the signal API is: Finclude void (*signal (int [Link], void (*handler) (int))) (int) ; ‘The formal argument of the API are: sig_no isa signal identifier like SIGINT or SIGTERM. The handler argument is the function pointer of a user-defined signal handler function, The following example attempts to catch the SIGTERM signal, ignores the SIGINT signal, and accepts the default action of the SIGSEGV signal. The pause API suspends the calling process until it is interrupted by a signal and the corresponding signal handler does a return: Hinclude #include /*signal handler function*/ void catch_sig(int { ig_num) signal (sig _num,catch_sig) ; LO , Prepared By: RAJKUMAR [Asst. Prof.] & DIVYA K [1RNO9ISO16] Page 2 RNSIT UNIX SYSTEM PROGRAMMING NOTES cout<<"catch_sig:"< T int sigprocnask(int cmd, const sigset_t *new mask, sigset_t old mask) ; Returns: Of OK, 1 on error The new_mask argument defines a set of signals to be set or reset in a calling process signal mask, and the cmd argument specifies how the new_mask value is to be used by the API, The possible values of cmd and the corresponding use of the new_mask value are: Core aaa red ‘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_mask argument to the calling process signal mask. ‘SIG_UNBLOCK Removes the signals specified in the new_mask argument from the calling process signal mask. If the actual argument to new_mask argument is a NULL pointer, the emd argument will be ignored, and the current process signal mask will not be altered. If the actual argument to old_mask is a NULL pointer, no previous signal mask will be returned, The sigset_t contains a collection of bit lags. The BSD UNIX and POSIX.1 define a set of API known as sigsetops functions: Winclude Ant sigemptyset (sigset_t* sigmask) ; int sigaddset (sige int sigdelset (sigset_t* signask, const int sig num); int sigfillset (sigset_t* sigmask) ; _t* sigmask, const int sig num); int sigismenber (const sigset_t* signask, const int sig num); Prepared By: RAJKUMAR [Asst. Prof.] & DIVYA K [1RNOSISOI6] Page 3 RNSIT UNIX SYSTEM PROGRAMMING NOTES ‘The sigemptyset API clears all signal flags in the sigmask argument. ‘The sigaddset API sets the flag corresponding to the signal_num signal in the sigmask argument. The sigdelset API clears the flag corresponding to the signal_nur signal in the sigmask argument. ‘The sigfllset API sets all the signal flags in the sigmask argument. [all the above functions return 0 if OK, -1 on error } > The sigismember API returns 1 if flag is set, 0 if not set and -1 if the cal falls. vv ‘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. Hincludecetato.2> ‘Hincludeceignal.2> Ant main() ‘ sigeet_t — signask; sigemptyset (ceignask) ; /Mindtialise set*/ Lf (eigprocnask (0,0, ésigmask)—=-1) /+get current signal mask*/ 1 perror ("sigprocmask") 7 exit (); ) else sigaddset (ceignask,SIGINT) ; /*set SIGINT flag*/ sigdelset (Ksignask, SIGSEGV) ; /*elear SIGSEGV flag*/ Lf (sigprocmask (SIG_SETMASK, ésignask, 0)==-1) perror ("sigproemask”) ‘Approcess can query which signals are pending for it via the sigpending API: Finclude int igpending(sigset_t* sigmask) ; Returns 0 if OK, -1if falls. ‘The sigpending API can be useful to find out whether one or more signals are pending for a process and to set up special signal handling methods for these signals before the process calls the sigprocmask API to unblock them. ‘The following example reports to the console whether the SIGTERM signal is pending for the process: Hinclude Hincludecstdio.h> #Hnclude int main() ‘ sigset_t — sigmask; sigenptyset (¢sigmask) ; Af (sigpending (¢signask)==-1) perror (“sigpending”) Prepared By: RAJKUMAR [Asst. Prof.] & DIVYA K [1RNO91S016] “Page? RNSIT UNIX SYSTEM PROGRAMMING NOTES else cout << "SIGTERM signal i: << (sigismenber (tsigmask,SIGTERM) ? “Set” : “No Set”) << endl; In addition to the above, UNIX also supports following APIs for signal mask manipulation: Winclude int sighold(int signal_num); int sigrelse(int signal_nun); int sigignore(int signal_num); int sigpause(int signal_num) ; SIGACTION The sigaction API blocks the signal it is catching allowing a process to specify additional signals to be blocked when the API is handling a signal. ‘The sigaction API prototype is: Winclude int sigaction(int signal_num, struct sigaction* action, struct sigaction* old action) ; Returns: 0 if OK, 1 on error The struct sigaction data type is defined in the header as: struct sigaction ‘ void (*sa_handler) (int) ; sigset_t a_mask; int ) The following program illustrates the uses of sigaction: Hincludeciostream.b> Hincludecstdio.h> Hinclude #include void callme(int sig_num) cl coutc<"catch signal:"< Hncludecetdio.2> Hncludecuntsed.b> #neludecsignal n> Hncludeceetjmp.b> sigimp_buf env: void calime(int sig_num) c coutc< “catch signa: < int kill(pid_t pid, int signal_num); Prepared By: RAJKUMAR [Asst. Prof.] & DIVYA K [1RNOSISO16] Page 7 RNSIT UNIX SYSTEM PROGRAMMING NOTES Returns: 0 on success, -1 on failure. ‘The signal_num argument is the integer value of a signal to be sent to one or more processes designated by pid. The Possible values of pid and its use by the kill API are: ‘The signal is sent to the process whose process I al 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 pid and for which the sender has permission to send the signal ‘The signal ls sent to all processes on the system for which the sender has permission to send the signal, pia The following program illustrates the implementation of the UNIK kill command using the kill API: Hincludeciostreas.t> Hinclodecetdio.2> Hincludecunistd.t> Hncludecstring.h> #includeceignal b> int main(int arge,char** argv) ‘ Ant pid, sig = SrGTERM; it (arge=3) t A¢ (secant (argy(1] ,"4d", 84g) !=1) cerr0) Af (secant (*++axgv, “td”, pid) —=1) ‘ Af (cil (pid, sig)==-1) perror ("ki11") ; ) else : cerr<<"invalid pid:” << argv{0] <. Where signal_num can be an integer number or the symbolic name ofa signal. is process 1D. . Prof.] & DIVYA K [1RNOSISO16] Page 8 RNSIT _UNIX SYSTEM PROGRAMMING NOTES EEE PROGRAMMING NOTES ALARM The alarm API canbe called by a process to request the kernel to send the IGALRM signal after a certain eumber of real elock seconds. The function prototype ofthe API is Winclude Unsigned int alarm(unsigned int time interval); Returns: 0 or number of seconds until previously set alarm The alarm API can be used to implement the sleep At Hincludeceignal.b> Hincludecstdio.n> Hincludecunietd.b> void wakeup( ) cr | wneisoad int steep (onsigned Sat tieer } struct sigaction action; action. sa_handler=vakeup; action.sa_flags=0, sigesptyset ([Link] mask) ; Af (sigaction (SIGALARM, caction,0)==-1) ‘ perror ("sigaction”) ; return -1; ) (void) alarm (timer); (void) pause( ); return 0; INTERVAL TIMERS The interval timer can be used to schedule a process to do some tasks ata fixed time interval, to time the execution of some operations, or to limit the time allowed for the execution of some tasks. The following program illustrates how to set up a real ime clock interval timer using the alarm API: Hinctudecstato.t> Hnetudecuntstd.t> Hincludeceignal.b> feting mNrERVAL 5 void caline (int sig_no) ‘ alarm (INTERVAL) ; /#do scheduled tasks*/ }) int main() Prepared By: RAJKUMAR [Asst. Prof.] & DIVYA K [1RNOSISO16] RNSIT UNIX SYSTEM PROGRAMMING NOTES struct sigaction action: sigenptyset (caction.2a_mask) ; action.sa_handler=(void(*) ( )) calime; action.sa_flagesSA RESTART; L¢(eigaction (STGALARM, gaction, 0) c 1) perror(*sigaction”) ; return 1; y Ae (alarm (INTERVAL) ==-1) perror ("alarm") ; else wnile(1) c /#do normal operation*/ ) return 0; > In addition to alarm API, UNIX also invented the setitimer API, which can be used to define up to three different types of timers in a process: = Real time clock timer + Timer based on the user time spent by a process = Timer based on the total user and system times spent by a process, ‘The getitimer APIs also defined for users to query the timer values that are set by the setitimer API. ‘The setitimer and getitimer function prototypes are: Winelude int setitimer(int which, const struct itimerval + val, struct itimerval * old); int getitimer(int which, struct itimerval * old); ‘The which arguments to the above APIs specify which timer to process. Its possible values and the corresponding timer types are: TTIMER_REAL | decrements in real time and generates a SIGALRM signal when it expires TTIMER_VIRTUAL | decrements in virtual time (time used by the process) and generates a SIGVTALRM signal when it expires. TFIMER_PROF | decrements in virtual time and system time for the process and generates 2 SIGPROF signal when it expires. The struct itimerval datatype is defined as: struct itimerval 1 struct timeval it_value; /tourrent value*/ struct timeval it_interval; (/* time interval*/ he — Prepared By: RAJKUMAR [Asst. Prof.] & DIVYA K [RNOSISO16] Page 10 Example program: Hncludecstato.2> #includecunistd.n> Hincludeceignal.p> define INTERVAL 5 void caline (int sig_no) ‘ (#40 scheduled tasks*/ , Ant maint) ‘ struct dtimerval val: struct sigaction action; sigemptyset (caction.ea_ mask) + action.aa_handler=(void(*)( )) caline; action.sa_flage=SA_RESTART; L£ (sigaction (STGALARM, caction,0)==-1) ‘ perror (*sigaction”) ; return 1; , val it interval. tv val .it_interval. ty_usec val.it_value.tv_sec [Link] value. ty_usec At (sotitiner (ITIMER REAL, cval , 0)==-1) perror(*alare”) ; eles wnite(2) c [#40 normal operation*/ The setitimer and getitimer APIs return a zero value if they succeed or a -1 value if they fal. POSIX.1b TIMERS POSIX.1b defines a set of APIs for interval timer manipulations. The POSIX.1b timers are more flexible and powerful | than are the UNIX timers in the following ways: * Users may define multiple independent timers per system clock. * The timer resolution is in nanoseconds. Users may specify the signal to be raised when a timer expires. The time interval may be specified as either an absolute or a relative time. RNSIT UNIX SYSTEM PROGRAMMING NOTES The POSIX.1b APIs for timer manipulations are: Wincludeceignal w> Hncludectine > int timer_create(clockid t clock, struct sigevent* spec, timer t* timer hdzp) ; Ant tiner_sottime(timer_t timer hdr, int flag, struct itinerspect val, struct itimerepect old) ; Ant tiner_gettine(timer_t timer hdr, struct itimerspect old) ; int timers et timer hdr); int timer delete (timer_t timer hdx) ; toverrun (tine: DAEMON PROCESSES TROD! IN Daemons are processes that live for a long time. They are often started when the system is bootstrapped and terminate only when the system is shut down, DAEMON CHARACTERISTICS The characteristics of daemons are: "Daemons run in background, = Daemons have super-user privilege. = Daemons don’t have controlling terminal, Daemons are session and group leaders. CODING RULES ‘Call umask to set the file mode creation mask to 0. The file mode creation mask that's inherited could be set to deny certain permissions. If the daemon process is going to create files, it may want to set specific permissions. * Gall fork and have the parent exit. This does several things. First, if the daemon was started as a simple shell command, having the parent terminate makes the shell think that the command is done. Second, the child inherits the process group 1D of the parent but gets a new process ID, so we're guaranteed that the child is not a process group leader. * Call setsid to create a new session. The process (a) becomes a session leader of a new session, (b) becomes the process group leader of a new process group, and (c) has no controlling terminal * Change the current working directory to the root directory. The current working directory inherited from the parent could be on a mounted file system. Since daemons normally exist until the system is rebooted, if the daemon stays on a mounted file system, that file system cannot be unmounted. * Unneeded file descriptors should be closed. This prevents the daemon from holding open any descriptors that it may have inherited from its parent. | "Some daemons open file descriptors 0, , and 2 to /dev/nut1 so that any library routines that try to read | from standard input or write to standard output or standard error will have no effect. Since the daemon is hot associated with a terminal device, there is nowhere for output to be displayed; nor is there anywhere to receive input from an interactive user. Even if the daemon was started from an interactive session, the daemon runs in the background, and the login session can terminate without affecting the daemon. If other Users log in on the same terminal device, we wouldn't want output from the daemon showing up on the terminal, and the users wouldn't expect their input to be read by the daemon, Prepared By: RAJKUMAR [Asst. Prof.] & DIVYA K [1RNOSISO16] page 12 RNSIT UNIX SYSTEM PROGRAMMING NOTES Example Program: Hinclude Hinclude #include Ant daenon_initialise( ) pid t pid; ie (( pid = for() ) < 0) ‘return ~1; eles 16 ( pid I= 0) ‘exit (0); /* parent exits */ /* child continues */ esi ) ehdi(*/"): vumask (0) return 0; , ERROR LOGGING ‘One problem a daemon has is how to handle error messages. It can't simply write to standard error, since it shouldn't have a controlling terminal. We don't want all the daemons writing to the console device, since on many workstations, the console device runs a windowing system. A central daemon error-logging facility is required Figure 13.2. The BSD sysios faciity erten toe oe vologgein users or seta anathe ost ' a : | [raewtes Yaew/xioa] | | [owe ps | : | ONikdoman Inert doin i | agian socket datagram socket 2o] ! There are three ways to generate log messages: = Kernel routines can call the 1og function. These messages can be read by any user process that opens and reads the /dev/klog device, * Most user processes (daemons) call the syslog(3) function to generate log messages. This causes the ‘message to be sent to the UNIX domain datagram socket /dev/log. + Auser process on this host, or on some other host that is connected to this host by a TCP/IP network, can send log messages to UDP port 514. Note that the syslog function never generates these UDP datagrams: they require explicit network programming by the process generating the log message. Normally, the syslogd daemon reads all tree forms of log messages. On start-up, this daemon reads a configuration file, usually /ete/[Link], which determines where different classes of messages are to be sent. For example, urgent messages can be sent to the system administrator (if logged in) and printed on the console, whereas warnings may be logged to file, Our interface to this facility is through the syslog function. Vinclude void openlog(const char *ident, int option, int facility); Prepared By: RAJKUMAR [Asst. Prof.] & DIVYA K [1RNO9ISO16] Page 13, RNSIT UNIX SYSTEM PROGRAMMING NOTES ey void syelog(int priority, const char “format, ...)7 void closelog(void) ; int setlogmask(int maskpri); ‘SINGLE-INSTANCE DAEMONS Some daemons are implemented so that only a single copy of the daemon should be running at a time for proper operation. The file and record-locking mechanism provides the basis for one way to ensure that only one copy of a daemon is running. If each daemon creates a file and places a write lock on the entire file, only one such write lock will be allowed to be created. Successive attempts to create write locks will fall, serving as an indication to successive copies of the daemon that another instance is already running. File and record locking provides a convenient mutual-exclusion mechanism. If the daemon obtains a write-lock on an entire file, the lock will be removed automatically if the daemon exits. This simplifies recovery, removing the need for us to clean up from the previous instance of the daemon. PROGRAM:Ensure that only one copy of a daemon is running Hinclude Hinclude include Hinclude include Hinclude Hinclude Hinclude define LOCKFILE "/var/run/[Link]" define LOCKMODE (S_IRUSR|S_IWUSR|S_IRGRP|S_TROTH) extern int lock#ile (int) ; int already_running(void) ‘ int fay char buf[16]; fd = open (LOCKFILE, 0_RDWR|O_CREAT, LOCKMODE) ; if (£4 < 0) { ‘syslog (LOG_ERR, “can't open exit(l); $e", LOCKFILE, strerror (errno); ) LE (Locktile(fd) < 0) { Lf (erzno == EACCES || errno == EAGATN) ( close (fa) ; return(1); ) syelog(L0G_ERR, “can't lock ts: $s", LOCKFILE, strerror(errno)); exit (1); ) Ftruncate (fd, 0) sprintf (buf, "81d", (1ong)getpid()) ; write(fd, buf, strlen (buf)+1): return (0); AEM IONS Ifthe daemon uses a lock file, the file is usually stored in /var/run. Note, however, that the daemon might need superuser permissions to create a file here. The name of the file is usually name. pid, where name is the name of the daemon or the service. For example, the name of the cron daemon's lock file is /var/run/[Link]. DN TTT EOP Prepared By: RAJKUMAR [Asst. Prof.] & DIVYA K [1RNO9ISO16] Page 14 UNIX SYSTEM PROGRAMMING NOTES If the daemon supports configuration options, they are usually stored in /etc. The configuration file is named name. conf, where name is the name of the daemon or the name of the service. For example, the Configuration for the syslogd daemon is /etc/sysiog..conf. Daemons can be started from the command line, but they are usually started from one of the system initialization scripts (/etc/xc* or /etc/init.d/*). Ifthe daemon should be restarted automatically when it exits, we can arrange for init to restart tif we include a respawn entry fort in /etc/inittab. fa daemon has a configuration file, the daemon reads it when it starts, but usually won't look at it again. If ‘an administrator changes the configuration, the daemon would need to be stopped and restarted to account for the configuration changes. To avoid this, some daemons will catch SIGKUP and reread their Configuration files when they receive the signal. Since they aren't associated with terminals and are either session leaders without controlling terminals or members of orphaned process groups, daemons have no ‘eason to expect to receive SIGHUP. Thus, they can safely reuse it CLIENT-SERVER MODE! In general, a server is a process that waits for a client to contact it, requesting some type of service. In Figure 13.2 [REFER PAGE 10], the service being provided by the syslogd server is the logging of an error message. {mn Figure 13.2, the communication between the client and the server is one-way. The client sends its service request to the server; the server sends nothing back to the client. In the upcoming chapters, we'll see numerous examples of two-way communication between a client and a server. The client sends a request to the server, and the server sends a reply back to the client, Prepared By: RAJKUMAR [Asst. Prof.] & DIVYA K [1RNOSISO16]

You might also like