Presentation is loading. Please wait.

Presentation is loading. Please wait.

1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 5: Signals, Time, Timers, and Token Rings.

Similar presentations


Presentation on theme: "1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 5: Signals, Time, Timers, and Token Rings."— Presentation transcript:

1

2 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 5: Signals, Time, Timers, and Token Rings

3 2GWU CS 259 Brad Taylor Spring 2004 Objectives SignalsSignals Systems Programming Project Status ReportSystems Programming Project Status Report Time & TimersTime & Timers Token Ring of Processes: IPC using PipesToken Ring of Processes: IPC using Pipes Final Scheduling: Monday, May 3, 2004 (Agreed)Final Scheduling: Monday, May 3, 2004 (Agreed) Last class week discussion/agreement “Rescheduled Mondays” & final study groupLast class week discussion/agreement “Rescheduled Mondays” & final study group

4 3GWU CS 259 Brad Taylor Spring 2004 Seeking Interested Students Middleware ++ Middleware ++ Habitats Habitats Complex Systems Proposals Complex Systems Proposals Interested Masters & Doctorate Students … Interested Masters & Doctorate Students … Weekly Wednesday evening meeting ~ 6:10 to 8:30 Weekly Wednesday evening meeting ~ 6:10 to 8:30 Food Provided!!! (usually snacks, but you never know) Food Provided!!! (usually snacks, but you never know) Many papers & degrees generated Many papers & degrees generated No ties required ;) No ties required ;)

5 4GWU CS 259 Brad Taylor Spring 2004 Signals What are they? Why use them? What are they? Why use them? Software Interrupts for asynchronous events Software Interrupts for asynchronous events What is their terminology? What is their terminology? How do they work? How do they work? Provide no information beyond signal name (an integer) Provide no information beyond signal name (an integer) How to deal with multiple processes, threads? Concurrency … How to deal with multiple processes, threads? Concurrency …

6 5GWU CS 259 Brad Taylor Spring 2004 Signals Terminology Signal generated when event causing signal occursSignal generated when event causing signal occurs Delivered when receiving process takes signal- based action Delivered when receiving process takes signal- based action Signal lifetime is interval between generation and deliverySignal lifetime is interval between generation and delivery A pending signal has been generated but not yet deliveredA pending signal has been generated but not yet delivered To catch a signal, the process executes a signal handler when the signal is deliveredTo 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 actionAlternatively, a process can ignore a signal as when delivered, taking no action

7 6GWU CS 259 Brad Taylor Spring 2004 Signals Terminology (con’t) The sigaction function specifies what a process does with a signal when delivered 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 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 Blocked signals are not delivered to a process until unblocked The sigprocmask function modifies a signal mask The sigprocmask function modifies a signal mask Each signal has a default action that usually terminates a process unless handled Each signal has a default action that usually terminates a process unless handled

8 7GWU CS 259 Brad Taylor Spring 2004 Signals Examples Control keys on terminal (CNTL-C, CNTL+SHIFT+2, etc.)Control keys on terminal (CNTL-C, CNTL+SHIFT+2, etc.) Hardware exceptions: divide by zero ( SIGFPE ), invalid memory reference ( SIGSEGV ), unaligned access ( SIGBUS )Hardware exceptions: divide by zero ( SIGFPE ), invalid memory reference ( SIGSEGV ), unaligned access ( SIGBUS ) kill() or kill – communicationkill() or kill – communication raise(sig) = kill(getpid(),sig) – note to selfraise(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 )Software conditions: child terminated ( SIGCHLD ), write on pipe w/o readers ( SIGPIPE ), timer expired ( SIGALM ), urgent data available at socket ( SIGURG )

9 8GWU CS 259 Brad Taylor Spring 2004 Required POSIX Signals SIGABRT : Abnormal termination signal caused by the abort() function (portable programs should avoid catching SIGABRT)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-outSIGALRM : The timer set by the alarm() function has timed-out SIGFPE : Arithmetic exception, such as overflow or division by zeroSIGFPE : Arithmetic exception, such as overflow or division by zero SIGHUP : Controlling terminal hangup or controlling process death detectedSIGHUP : Controlling terminal hangup or controlling process death detected SIGILL : Illegal instruction indicating program error; Applications may catch this signal and attempt to recover from bugsSIGILL : Illegal instruction indicating program error; Applications may catch this signal and attempt to recover from bugs SIGINT : Interrupt special character typed on controlling keyboardSIGINT : Interrupt special character typed on controlling keyboard SIGKILL : Termination signal: cannot be caught or ignoredSIGKILL : Termination signal: cannot be caught or ignored SIGPIPE : Write to a pipe with no readersSIGPIPE : Write to a pipe with no readers SIGQUIT : Quit special character typed on controlling keyboardSIGQUIT : Quit special character typed on controlling keyboard SIGSEGV : Invalid memory reference. Like SIGILL, portable programs should not intentionally generate invalid memory referencesSIGSEGV : Invalid memory reference. Like SIGILL, portable programs should not intentionally generate invalid memory references SIGTERM : Termination signalSIGTERM : Termination signal SIGUSR1, SIGUSR2 : Application-defined signal 1 & 2SIGUSR1, SIGUSR2 : Application-defined signal 1 & 2

10 9GWU CS 259 Brad Taylor Spring 2004 POSIX Job Control Signals SIGCHLD : Child process terminated or stopped; by default, this signal is ignoredSIGCHLD : Child process terminated or stopped; by default, this signal is ignored SIGCONT : Continue the process if it is currently stopped; otherwise, ignore the signalSIGCONT : Continue the process if it is currently stopped; otherwise, ignore the signal SIGSTOP : Stop signal; cannot be caught or ignoredSIGSTOP : Stop signal; cannot be caught or ignored SIGTSTP : Stop special character typed on the controlling keyboardSIGTSTP : Stop special character typed on the controlling keyboard SIGTTIN : Read from the controlling terminal attempted by a background process groupSIGTTIN : Read from the controlling terminal attempted by a background process group SIGTTOU : Write to controlling terminal attempted by a member of a background process groupSIGTTOU : Write to controlling terminal attempted by a member of a background process group

11 10GWU CS 259 Brad Taylor Spring 2004 Sending Signals A signal can be sent to a process from the command line using killA 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:From program the kill system call can be used: #include #include int kill(pid_t pid, int sig);

12 11GWU CS 259 Brad Taylor Spring 2004 Signal Mask and Signal Sets Dealing with collections of signals has evolvedDealing with collections of signals has evolved Originally, an int held a collection of bits, one per signal; now, signal sets of type sigset_t usedOriginally, an int held a collection of bits, one per signal; now, signal sets of type sigset_t used #include #include 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

13 12GWU CS 259 Brad Taylor Spring 2004 Signal Mask and Sets (con’t) The process signal mask is a set of blocked signalsThe process signal mask is a set of blocked signals A blocked signal remains pending after generation until unblockedA blocked signal remains pending after generation until unblocked This mask is modified with the sigprocmask system call:This mask is modified with the sigprocmask system call: #include #include int sigprocmask(int how, const sigset_t *set, sigset_t *oset); The how can be: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 NULLEither set (pointer to signal set to be modified) or oset (returned original signal set before modification) may be NULL

14 13GWU CS 259 Brad Taylor Spring 2004 Catching and Ignoring Signals #include #include 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 NULLEither act or oact may be NULL To handle signal, process must be scheduled to runTo handle signal, process must be scheduled to run SIG_IGN specifies receiving & disposing of signal; what about SIG_DFL ?SIG_IGN specifies receiving & disposing of signal; what about SIG_DFL ?

15 14GWU CS 259 Brad Taylor Spring 2004 Waiting for Signals pause, sigsuspend and sigwait evolved as well to avoid “Busy Waiting” (What is “Busy Waiting”?)pause, sigsuspend and sigwait evolved as well to avoid “Busy Waiting” (What is “Busy Waiting”?) #include #include int pause(void); If signal received between testing and the pause, may block foreverIf signal received between testing and the pause, may block forever Solution: atomically unblock the signal and suspend the processSolution: atomically unblock the signal and suspend the process #include #include 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 receivedSets 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 returningSignal 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 handledsigwait blocks any specified signal, removes that signal when handled, and returns that signal’s value when handled

16 15GWU CS 259 Brad Taylor Spring 2004 System Calls and Signals Problems: system call interruption & non-reentrant system calls System Call Interruption : System Call Interruption : Some system calls that can block indefinitely long:Some system calls that can block indefinitely long: return -1 when a signal is delivered and set errno to EINTRreturn -1 when a signal is delivered and set errno to EINTR These system calls are identified on their man pages (return values list)These system calls are identified on their man pages (return values list) Two that require special attention: read and writeTwo that require special attention: read and write How would you handle a program segment to restart a read if interrupted by a signal?How would you handle a program segment to restart a read if interrupted by a signal? The write system should be handled similarlyThe write system should be handled similarly Recall that you also need to handle a write that does not write as many bytes as requestedRecall that you also need to handle a write that does not write as many bytes as requested

17 16GWU CS 259 Brad Taylor Spring 2004 System Calls and Signals (con’t) Non-reentrant system calls : Non-reentrant system calls : A function that can be safely called from a signal handler is called async-signal-safeA function that can be safely called from a signal handler is called async-signal-safe Recall that functions like strtok are not async-signal-safeRecall 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 followedSee 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 includedNote that the C I/O functions such as fprintf are not included These may be safe under some implementations but not under othersThese 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!Although under Solaris, almost everything is async-signal-safe if it can be, for compatibility, don’t assume other calls are safe!

18 17GWU CS 259 Brad Taylor Spring 2004 Signal Handler as Alarm Clock #include #include int i, j; void alarm_handler(int dummy) { printf("Three seconds just passed: j = %d. i = %d\n", j, i); printf("Three seconds just passed: j = %d. i = %d\n", j, i); signal(SIGALRM, alarm_handler); signal(SIGALRM, alarm_handler);}main(){ alarm(3); alarm(3); for (j = 0; j < 200; j++) { for (j = 0; j < 200; j++) { for (i = 0; i < 1000000; i++); for (i = 0; i < 1000000; i++); }}

19 18GWU CS 259 Brad Taylor Spring 2004 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

20 19GWU CS 259 Brad Taylor Spring 2004 Handling Time Motivation: second fractions count 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.1 10 = 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 – T e = (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! Some code time calculations had been improved, others not, actually aggravating problem as inaccuracies no longer cancelled! BOOM!

21 20GWU CS 259 Brad Taylor Spring 2004 Clocks and Timers Provide current time, elapsed time, timerProvide current time, elapsed time, timer If programmable interval time used for timings, periodic interruptsIf programmable interval time used for timings, periodic interrupts ioctl (on UNIX) covers odd aspects of I/O such as clocks and timersioctl (on UNIX) covers odd aspects of I/O such as clocks and timers User interest and operating system interest (scheduler, for example)User interest and operating system interest (scheduler, for example) How do we handle time for a distributed system?How do we handle time for a distributed system?

22 21GWU CS 259 Brad Taylor Spring 2004 Unix time Command Accurately timing things on computers is essential for: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 accessFor 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”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: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

23 22GWU CS 259 Brad Taylor Spring 2004 Timing Programs What Do We Measure?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'tsDos 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?)Timing Programs in Java (wall clock; else?)

24 23GWU CS 259 Brad Taylor Spring 2004 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 systemsOften 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 constraintsWell-defined fixed-time constraints Real-Time systems may be either hard or soft real-timeReal-Time systems may be either hard or soft real-time

25 24GWU CS 259 Brad Taylor Spring 2004 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 ";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 environmentReal-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 constraints derived from physical impact of controlling systems activities, hard and soft constraints Timing constraints derived from physical impact of controlling systems activities, hard and soft constraints –Periodic Tasks: Time-driven recurring at regular intervals –Aperiodic: Event-driven

26 25GWU CS 259 Brad Taylor Spring 2004 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

27 26GWU CS 259 Brad Taylor Spring 2004 Typical Real-Time System Controlling System Environment sensor actuator Controlled System  ACTUATOR DESIRED RESPONSE FEEDBACK ELEMENTS {SENSOR(s)} + _ Error SOFTWARE CONTROL {PID, MBC, etc.} ENVIRONMENT {Temp, Pres, D/P, Flow, etc.} PLANT CONDI- TIONING

28 27GWU CS 259 Brad Taylor Spring 2004 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

29 28GWU CS 259 Brad Taylor Spring 2004 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

30 29GWU CS 259 Brad Taylor Spring 2004 Token Ring of Processes Example of pipes supporting Inter- Process Communication Course web page link to text author’s java applet …


Download ppt "1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 5: Signals, Time, Timers, and Token Rings."

Similar presentations


Ads by Google