UNIX Programming - Module 5 Slides
UNIX Programming - Module 5 Slides
Triggered by events and posted on a process to notify it that something has happened
and requires some action.
Event can be generated from a process, a user or the UNIX kernel.
Parent and child processes can send signals to each other for process synchronization.
Signals are the software version of hardware interrupts.
Signals are defined as integer flags.
<signal.h> header depicts the list of signals defined for a UNIX system.
2
SIGNALS
3
SIGNALS
4
SIGNALS
5
SIGNALS
Process may set up per-signal handling mechanisms – ignores some signals, catches
some other signals and accepts default action from the remaining signals.
Process may change handling of certain signals in its course of execution.
Signal is said to have been delivered if it has been reacted to by the recipient process.
Default action for most signals – terminate a recipient process.
Some signals will generate a core file for the aborted process – users can trace back
the state of the process when it was aborted.
These signals are usually generated when there is an implied program error in the
aborted process.
6
SIGNALS
Most signals can be ignored or caught except SIGKILL and SIGSTOP signals.
Companion signal to SIGSTOP is SIGCONT, which resumes a process
execution after it has been stopped.
Process is allowed to ignore certain signals so that it is not interrupted while doing
certain mission-critical work.
Signal handler function cleans up the work environment of a process before
terminating the process gracefully.
7
KERNEL SUPPORT FOR SIGNALS
UNIX System V.3 - each entry in kernel process table slot has array of signal flags,
one for each signal defined in the system.
When a signal is generated for a process, kernel will set the corresponding signal
flag in the process table slot of the recipient process.
If recipient process is asleep, kernel will awaken the process by scheduling it.
When recipient process runs, kernel will check the process U-area that contains an
array of signal handling specifications.
Each entry of the array corresponds to a signal defined in the system.
Kernel will consult the array to find out how the process will react to the pending
signal.
8
KERNEL SUPPORT FOR SIGNALS
UNIX System V.2 - when a signal is caught, kernel will first reset the signal handler
in the recipient process U-area, then call the user signal handling function specified
for that signal.
Multiple instances of a signal being sent to a process at different points – the
process will catch only the first instance of the signal.
All subsequent instances of the signal – handled in the default manner.
Continuously catching multiple occurrences of a signal – process must reinstall the
signal handler function every time the signal is caught.
Time between signal handler invoking and re-establishment of signal handler method
- another instance of signal may be delivered to the process. Leads to race condition.
9
KERNEL SUPPORT FOR SIGNALS
Solving the unreliability of signal handling in UNIX System V.2 - BSD UNIX 4.2 and
POSIX.1 use alternate method.
When a signal is caught – kernel does not reset the signal handler, so there is no need
for the process to re-establish the signal handling method.
Kernel will block further delivery of the same signal to the process until the signal
handler function has completed execution.
Ensures that signal handler function will not be invoked recursively for multiple
instances of the same signal.
10
SIGNAL API
12
SIGNAL API
13
SIGNAL MASK
14
SIGNAL MASK
new_mask – defines a set of signals to be set or reset in a calling process signal mask.
cmd – specifies how the new_mask value is to be used by the API.
Returns: 0 if it succeeds, -1 if it fails.
Possible failure - new_mask/old_mask are invalid addresses.
15
SIGNAL MASK
cmd Value 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_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 actual argument to new_mask argument is NULL pointer – cmd argument will be ignored
and current process signal mask will not be altered.
old_mask argument – address of a sigset_t variable that will be assigned the original signal
mask of calling process prior to sigprocmask call.
If actual argument to old_mask is NULL pointer, no previous signal mask will be returned.
16
SIGNAL MASK
sigset_t is a data type defined in <sigset.h> - contains a collection of bit flags, with
each bit flag representing one signal defined in a given system.
sigsetops functions - set of API defined by BSD UNIX and POSIX.1 to set, reset and
query the presence of signals in a sigset_t typed variable.
17
SIGNAL MASK
18
SIGNAL MASK
One or more signals are pending for a process and are unblocked via sigprocmask API –
the signal handler methods for those signals that are in effect at the time of
sigprocmask call will be applied before the API is returned to caller.
Multiple instances of the same signal pending for the process – implementation-
dependent whether one or all the instances will be delivered to the process.
Process can query which signals are pending for it using sigpending API:
sigmask – address of a sigset_t typed variable; assigned the set of signals pending for the
calling process by the API.
19
SIGNAL MASK
20
SIGNAL MASK
sighold API – adds the named signal signal_num to the calling process signal mask.
sigrelse API – removes the named signal signal_num for the calling process signal
mask.
sigignore API – sets the handling method for the named signal signal_num to
SIG_DFL
sigpause API – removes the named signal signal_num from the calling process signal
mask and suspends the process until it is interrupted by a signal.
21
SIGACTION
Replacement for signal API in the latest UNIX and POSIX systems.
sigaction API - called by a process to set up a signal handling method for each signal
it wants to deal with.
Passes back the previous signal handling method for a given signal.
Blocks the signal it is catching, allowing a process to specify additional signals to be
blocked when the API is handling a signal.
22
SIGACTION
Prototype of sigaction API:
23
SIGACTION
24
SIGACTION
25
SIGACTION
26
SIGACTION
When a child process terminates or stops, kernel will generate a SIGCHLD signal to
its parent process.
Three different events may occur depending on how the parent sets up the handling of
the SIGCHLD signal.
28
SIGCHLD SIGNAL AND THE WAITPID API
30
SIGCHLD SIGNAL AND THE WAITPID API
31
SIGCHLD SIGNAL AND THE WAITPID API
32
SIGCHLD SIGNAL AND THE WAITPID API
Interaction between SIGCHLD and wait API is the same as that between SIGCHLD
and waitpid API.
Earlier versions of UNIX used the SIGCLD signal instead of SIGCHLD.
SIGCLD signal is now obsolete, but most of the latest UNIX systems have defined
SIGCLD to be the same as SIGCHLD for backward compatibility.
32
SIGSETJMP AND SIGLONGJMP APIS
34
SIGSETJMP AND SIGLONGJMP APIS
35
SIGSETJMP AND SIGLONGJMP APIS
signal_num – integer value of a signal that must be sent to one or more processes
designated by pid.
Possible values
pid Value Effectsofonpid: positive value, 0, -1, negative value.
kill API
positive value pid is a process ID. Sends signal_num to that process.
0 Sends signal_num to all processes whose process GID is same as the calling process
-1 Sends signal_num to all process whose real UID is same as the effective UID of calling
process.
If calling process effective UID is the superuser UID, signal_num will be sent to all
processes in the system (except process 0 and process 1).
negative Sends signal_num to all processes whose process GID matches absolute value of pid
value
37
KILL
38
ALARM
Can be called by a process to request the kernel to send the SIGALRM signal after a
certain number of real clock seconds.
alarm API function prototype:
Returns: number of CPU seconds left in the process timer, as set by previous
alarm system call.
time_interval – number of CPU seconds elapsed time, after which the kernel will send
the SIGALRM signal to the calling process.
If time_interval = 0, it turns off the alarm clock.
40
ALARM
Effect of previous alarm is cancelled and process timer is reset with new alarm call.
Process alarm clock is not passed on to its forked child, but an execed process retains
the same alarm clock value as was prior to the exec API call.
alarm API is used to implement sleep API – suspends a calling process for the
specified number of CPU seconds.
Process will be awakened by either the elapsed time exceeding the timer value or
when the process is interrupted by a signal.
40
ALARM
42
INTERVAL TIMERS
42
INTERVAL TIMERS
Additional features of setitimer API:
alarm resolution time is in seconds.
setitimer resolution time is in microseconds.
alarm can be used to set up 1 real-time clock timer per process.
setitimer can set up 3 - real-time clock timer, timer based on user time spent by a
process, timer based on total user time and system times spent by a process.
43
INTERVAL TIMERS
45
INTERVAL TIMERS
For setitimer API – it_value is the time to set the named timer, it_interval is the time
to reload the timer when it expires.
For getitimer API – it_value is the named timer's remaining time to expiration,
it_interval is the time to reload the timer when it expires.
46
POSIX.1B TIMERS
47
POSIX.1B TIMERS
POSIX timers created by a process are not inherited by its child process, but are
retained across the exec system call.
Unlike UNIX timers, POSIX timer can be used safely with sleep API if it does not
use the SIGALRM signal when it expires.
48
POSIX.1B TIMERS
timer_create API – used to dynamically create a timer and return its handler.
clock argument – specifies which system clock the new timer should be based on.
clock value may be CLOCK_REALTIME for creating a real-time clock timer.
spec argument – defines what action to take when the timer expires.
49
POSIX.1B TIMERS
timer_getoverrun API – returns the number of signals generated by a timer but was
lost / overrun.
timer_delete API – used to destroy a timer created by timer_create API.
50
DAEMONS
51
DAEMONS
52
DAEMON CHARACTERISTICS
53
DAEMON CHARACTERISTICS
54
DAEMON CHARACTERISTICS
keventd daemon – provides process context for running scheduled functions in the
kernel.
kapmd daemon – provides support for the advanced power management
features available with various computer systems.
kswapd daemon – supports the virtual memory subsystem by writing dirty pages to
disk slowly over time, so the pages can be reclaimed. (a.k.a pageout daemon)
bdflush daemon – flushes dirty buffers from the buffer cache back to disk when
available memory reaches a low-water mark.
kupdated daemon – flushes dirty pages back to disk at regular intervals to decrease
data loss in the event of a system failure.
55
DAEMON CHARACTERISTICS
57
CODING RULES
59
CODING RULES
59
CODING RULES
61
CODING RULES
61
CODING RULES
63
CODING RULES
Rule 6 – Open file descriptors 0, 1, and 2 to /dev/null so that any library routines that
try to read from standard input or write to standard output or standard error will have
no effect.
Daemon is not 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.
Other users log in on the same terminal device – output from the daemon should
not show up on the terminal, and input from users should not be read by daemon.
63
ERROR LOGGING
64
ERROR LOGGING
65
ERROR LOGGING
66
ERROR LOGGING
67
ERROR LOGGING
68
ERROR LOGGING
69
ERROR LOGGING
70
ERROR LOGGING
option Description
LOG_CONS If the log message cannot be sent to syslogd via the UNIX domain datagram, the
message is written to the console instead.
LOG_NDELAY Open the UNIX domain datagram socket to the syslogd daemon immediately; do not
wait until the first message is logged.
LOG_NOWAIT Do not wait for child processes that might have been created in the process of logging
the message.
LOG_ODELAY Delay the open of the connection to the syslogd daemon until the first message is
logged.
LOG_PERROR Write the log message to standard error in addition to sending it to syslogd.
LOG_PID Log the process ID with each message. This is intended for daemons that fork a child
process to handle different requests.
72
ERROR LOGGING
facility – lets the configuration file specify that messages from different facilities are
to be handled differently.
If we do not call openlog, or if we call it with a facility of 0, we can still specify the
facility as part of the priority argument to syslog.
Single UNIX Specification – defines only a subset of the facility codes
typically available on a given platform.
73
ERROR LOGGING
facility Description
LOG_AUTH Authorization programs such as login, su, getty
LOG_AUTHPRIV Same as LOG_AUTH, but logged to file with restricted permissions
LOG_CRON cron and at
LOG_DAEMON System daemons such as inetd, routed
LOG_FTP FTP daemon ftpd
LOG_KERN Messages generated by the kernel
LOG_LOCAL0 to Reserved for local use
LOG_LOCAL7
73
ERROR LOGGING
facility Description
LOG_LPR Line printer system functions such as lpd, lpc
LOG_MAIL Mail system
LOG_NEWS Usenet network news system
LOG_SYSLOG syslogd daemon itself
LOG_USER Messages from other user processes
LOG_UUCP UUCP system
74
ERROR LOGGING
level – orderedDescription
level by priority, from highest to lowest.
LOG_DEBUG Debug message (lowest priority)
LOG_INFO Informational message
LOG_NOTICE Normal, but significant condition
LOG_WARNING Warning condition
LOG_ERR Error condition
LOG_CRIT Critical condition (such as hard device error)
LOG_ALERT Condition that must be fixed immediately
LOG_EMERG Emergency – system is unusable (highest priority)
75
ERROR LOGGING
76
ERROR LOGGING
When the log priority mask is set, messages are not logged unless their priority is
set in the log priority mask.
Attempts to set the log priority mask to 0 will have no effect.
logger program – provided by many systems to send log messages to the syslog
facility.
Optional arguments – specifies the facility, level, and ident.
Single UNIX Specification does not define any options.
Intended for a shell script running non-interactively that needs to generate log
messages.
78
ERROR LOGGING
78
ERROR LOGGING
79
CLIENT-SERVER MODEL
81
THANK YOU