290 likes | 441 Views
Systems Programming. Meeting 5: Signals, Time, Timers, and Token Rings. Objectives. Signals Systems Programming Project Status Report Time & Timers Token Ring of Processes: IPC using Pipes Final Scheduling: Monday, May 3, 2004 (Agreed)
E N D
Systems Programming Meeting 5: Signals, Time, Timers, and Token Rings
Objectives • Signals • Systems Programming Project Status Report • Time & Timers • Token Ring of Processes: IPC using Pipes • Final Scheduling: Monday, May 3, 2004 (Agreed) • Last class week discussion/agreement “Rescheduled Mondays” & final study group
Seeking Interested Students • Middleware ++ • Habitats • Complex Systems Proposals • Interested Masters & Doctorate Students … • Weekly Wednesday evening meeting ~ 6:10 to 8:30 • Food Provided!!! (usually snacks, but you never know) • Many papers & degrees generated • No ties required ;)
Signals • What are they? Why use them? • Software Interrupts for asynchronous events • What is their terminology? • How do they work? • Provide no information beyond signal name (an integer) • How to deal with multiple processes, threads? Concurrency …
Signals Terminology • Signal generated when event causing signal occurs • Delivered when receiving process takes signal-based action • Signal lifetime is interval between generation and delivery • A pendingsignal has been generated but not yet delivered • To catch a signal, the process executes a signal handler when the signal is delivered • Alternatively, a process can ignore a signal as when delivered, taking no action
Signals Terminology (con’t) • The sigaction function specifies what a process does with a signal when delivered • The receiving process’ signal mask determines when action is taken for a generated signal, composed of signals to be blocked • Blocked signals are not delivered to a process until unblocked • The sigprocmask function modifies a signal mask • Each signal has a default action that usually terminates a process unless handled
Signals Examples • Control keys on terminal (CNTL-C, CNTL+SHIFT+2, etc.) • Hardware exceptions: divide by zero (SIGFPE), invalid memory reference (SIGSEGV), unaligned access (SIGBUS) • kill() or kill – communication • raise(sig) = kill(getpid(),sig) – note to self • Software conditions: child terminated (SIGCHLD), write on pipe w/o readers (SIGPIPE), timer expired (SIGALM), urgent data available at socket (SIGURG)
Required POSIX Signals • SIGABRT: Abnormal termination signal caused by the abort() function (portable programs should avoid catching SIGABRT) • SIGALRM: The timer set by the alarm() function has timed-out • SIGFPE: Arithmetic exception, such as overflow or division by zero • SIGHUP: Controlling terminal hangup or controlling process death detected • SIGILL: Illegal instruction indicating program error; Applications may catch this signal and attempt to recover from bugs • SIGINT: Interrupt special character typed on controlling keyboard • SIGKILL: Termination signal: cannot be caught or ignored • SIGPIPE: Write to a pipe with no readers • SIGQUIT: Quit special character typed on controlling keyboard • SIGSEGV: Invalid memory reference. Like SIGILL, portable programs should not intentionally generate invalid memory references • SIGTERM: Termination signal • SIGUSR1, SIGUSR2: Application-defined signal 1 & 2
POSIX Job Control Signals • SIGCHLD: Child process terminated or stopped; by default, this signal is ignored • SIGCONT: Continue the process if it is currently stopped; otherwise, ignore the signal • SIGSTOP: Stop signal; cannot be caught or ignored • SIGTSTP: Stop special character typed on the controlling keyboard • SIGTTIN: Read from the controlling terminal attempted by a background process group • SIGTTOU: Write to controlling terminal attempted by a member of a background process group
Sending Signals • A signal can be sent to a process from the command line using kill • kill -l lists signals system understands • kill [-signal] pid sends a signal to a process (optional argument is a name or number; default SIGTERM) • To unconditionally kill a process, use:kill -9 pid which is kill -KILL pid • From program the kill system call can be used: #include <sys/types.h> #include <signal.h> int kill(pid_t pid, int sig);
Signal Mask and Signal Sets • Dealing with collections of signals has evolved • Originally, an int held a collection of bits, one per signal; now, signal sets of type sigset_t used • #include <signal.h> • int sigemptyset(sigset_t *set); initializes to contain no signals • int sigfillset(sigset_t *set); put all signals in the set • int sigaddset(sigset_t *set, int signo); add one signal to set • int sigdelset(sigset_t *set, int signo); removes one signal • int sigismember(const sigset_t *set, int signo); tests to see if a signal is in the set
Signal Mask and Sets (con’t) • The process signal mask is a set of blocked signals • A blocked signal remains pending after generation until unblocked • This mask is modified with the sigprocmask system call: • #include <signal.h> • int sigprocmask(int how, const sigset_t *set, sigset_t *oset); • The how can be: • SIG_BLOCK • SIG_UNBLOCK • SIG_SETMASK • Either set (pointer to signal set to be modified) or oset (returned original signal set before modification) may be NULL
Catching and Ignoring Signals • #include <signal.h> • int sigaction(int signo, const struct sigaction *act, struct sigaction *oact); • struct sigaction { • void (*sa_handler)(); /* SIG_DFL, SIG_IGN, or • pointer to function */ • sigset_t sa_mask; /* additional signals to be blocked • during execution of handler */ • int sa_flags; /* special flags and options */ • }; • Either act or oact may be NULL • To handle signal,process must be scheduled to run • SIG_IGN specifies receiving & disposing of signal; what about SIG_DFL?
Waiting for Signals • pause, sigsuspend and sigwait evolved as well to avoid “Busy Waiting” (What is “Busy Waiting”?) • #include <unistd.h> • int pause(void); • If signal received between testing and the pause, may block forever • Solution:atomically unblock the signal and suspend the process • #include <signal.h> • int sigsuspend(const sigset_t *sigmask); • Sets the signal mask to the one pointed to by sigmask and suspends the process until a signal is received • Signal mask restored to what it was before being called when returning • sigwait blocks any specified signal, removes that signal when handled, and returns that signal’s value when handled
System Calls and Signals • Problems: system call interruption & non-reentrant system calls • System Call Interruption: • Some system calls that can block indefinitely long: • return -1 when a signal is delivered and set errno to EINTR • These system calls are identified on their man pages (return values list) • Two that require special attention: read and write • How would you handle a program segment to restart a read if interrupted by a signal? • The write system should be handled similarly • Recall that you also need to handle a write that does not write as many bytes as requested
System Calls and Signals (con’t) • Non-reentrant system calls: • A function that can be safely called from a signal handler is called async-signal-safe • Recall that functions like strtok are not async-signal-safe • See table in text for a complete list of function calls that must be async-signal-safe if the POSIX standard is followed • Note that the C I/O functions such as fprintf are not included • These may be safe under some implementations but not under others • Although under Solaris, almost everything is async-signal-safe if it can be, for compatibility, don’t assume other calls are safe!
Signal Handler as Alarm Clock • #include <signal.h> • int i, j; • void alarm_handler(int dummy) • { • printf("Three seconds just passed: j = %d. i = %d\n", j, i); • signal(SIGALRM, alarm_handler); • } • main() • { • signal(SIGALRM, alarm_handler); • alarm(3); • for (j = 0; j < 200; j++) { • for (i = 0; i < 1000000; i++); • } • }
Project Status Report • Group I: Dan, Ricardo & Kamal / Wire Socket • Group II: Clayton, Jason / Named Pipes • Group IIIa: Brooke, Emry / Shared Memory & Futexs • Group IIIb: Nush, Ram / Shared Memory & Semaphores • Issues to discuss: • Error checking • Rough draft code submission for integration review • Further Guidance, Questions
Handling Time BOOM! • Motivation: second fractions count • Original Patriot missed Scud intercept: 28 solders die, 100 injured • Internal clock calibrated in tenth-seconds (tick = 1/10 sec) • Multiplied by 1/10 => Time (seconds) • 0.110 = 0.0001100110011…2 • 24-bit truncated calculations • error = 1.10011… x 2-24 ≈ 9.5 x 10-8 /tick • Tracking system operating 100 hours w/o reboot • Te=(9.5 x 10-8 e/tick)(100 hr)(60 min/hr )(60 sec/min)(10 ticks/sec) ≈ 0.34 sec • Scud speed 1676 m/sec => • > ½ km error, exceeding “range gate” • Some code time calculations had been improved, others not, actually aggravating problem as inaccuracies no longer cancelled!
Clocks and Timers • Provide current time, elapsed time, timer • If programmable interval time used for timings, periodic interrupts • ioctl (on UNIX) covers odd aspects of I/O such as clocks and timers • User interest and operating system interest (scheduler, for example) • How do we handle time for a distributed system?
Unix timeCommand • Accurately timing things on computers is essential for: • performance analysis • identification of bottlenecks in programs • experimental determination of computational efficiency • For large scale problems it is also important to track down memory activity such as page faults; in this case, the data read in from disk can require 10-1000 times as long to access • I/O activity such as periodic output of computation state: although not always avoidable, sometimes this can be made more efficient by writing output files in binary format, or by spawning a separate output “thread” • The simplest way to time a program on a UNIX machine is to use the time command: enter your typical command line after it: • time make -k
Timing Programs • What Do We Measure? • Wall clock time: All other programs running, taking CPU away from you • Unix time: the amount of time processor actually spends running your program • Dos and Don'ts • Machine should be relatively quiet • No one cares about wall clock time • Time only your algorithm (avoid I/O, extraneous) • Never time user input • Repeat your computation several times • Timing Programs in Java (wall clock; else?)
Real-Time Systems • Often used for control devices in dedicated applications such as controlling scientific experiments, medical imaging systems, industrial control systems, and some display systems • Well-defined fixed-time constraints • Real-Time systems may be either hard or soft real-time
Real-Time Characteristics • Real-time systems defined as: "those systems in which the correctness of the system depends not only on the logical result of the computation, but also on the time at which the results are produced"; • J. Stankovic, "Misconceptions About Real-Time Computing," IEEE Computer, 21(10), October 1988. • Real-time systems often comprised of a controlling system, controlled system and environment • Controlling system: acquires information about environment using sensors and controls the environment with actuators • Timing constraintsderived from physical impact of controlling systems activities, hard and soft constraints • Periodic Tasks: Time-driven recurring at regular intervals • Aperiodic: Event-driven
Hard & Soft Real-Time • Hard real-time failure to meet constraint is a fatal fault; validated system always meets timing constraints: • Secondary storage limited or absent, data stored in short term memory, or read-only memory (ROM) • Conflicts with time-sharing systems, not supported by general-purpose operating systems • Deterministic constraints • Probabilistic constraints • Constraints in terms of some usefulness function • Soft real-time late completion is undesirable but generally not fatal; no validation or only demonstration job meets some statistical constraint; occasional missed deadlines or aborted execution is usually considered tolerable; often specified in probabilistic terms • Limited utility in industrial control of robotics • Useful in applications (multimedia, virtual reality) requiring advanced operating-system features
DESIRED RESPONSE CONDI-TIONING + SOFTWARECONTROL {PID, MBC, etc.} ACTUATOR PLANT _ ENVIRONMENT{Temp, Pres, D/P, Flow, etc.} sensor actuator Error actuator sensor FEEDBACK ELEMENTS{SENSOR(s)} sensor actuator sensor actuator Typical Real-Time System Controlled System Controlling System Environment
Other Real-Time Concerns • Determinism - one measure: delay between interrupt assertion and executing the ISR • Responsiveness - time to service interrupt • User Control • Reliability • Fail-soft operation
Developing a Reference Model • Modeling the system to focus on timing properties and resource requirements. Composed of three elements: • workload model - describes supported applications • Temporal parameters • Precedence constraints and dependencies • Functional parameters • resource model - describes available system resources • Modeling resources (Processors and Resources) • Resource parameters • algorithms - how application uses resources at all times • Scheduling Hierarchy
Token Ring of Processes • Example of pipes supporting Inter-Process Communication • Course web page link to text author’s java applet …