Timers Timer – Keeps track of the passage of time Simple Timer – Measures elapsed time, reporting it when queried Interval Timer – –Generates an interrupt.

Slides:



Advertisements
Similar presentations
Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 10 SHARED MEMORY.
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Chapter 9 Times and Timers Source: Robbins and Robbins, UNIX Systems Programming, Prentice Hall, 2003.
System Files and Process Environment Password file Group file System identification Time Process environment.
The Process Control Block From: A Process Control Block (PCB, also called Task Control Block or Task Struct) is.
I/O Multiplexing Road Map: 1. Motivation 2. Description of I/O multiplexing 3. Scenarios to use I/O multiplexing 4. I/O Models  Blocking I/O  Non-blocking.
Critical Sections and Semaphores A critical section is code that contains access to shared resources that can accessed by multiple processes. Critical.
1 Homework / Exam HW7 due class 25 Exam 3 - class 26 –Open Book, Open Notes –Covers up through end of K&R 7 –and Appendix B Standard Library –Plus UNIX.
SignalsSignals. What is a Signal? A signal is a notification that some event has occurred. Usually a signal is sent to a process asynchronously and whatever.
Timers Timer – Keeps track of the passage of time Simple Timer – Measures elapsed time, reporting it when queried Interval Timer – –Generates an interrupt.
Exec function Exec function: - replaces the current process (its code, data, stack & heap segments) with a new program - the new program starts executing.
CS Lecture 17 Outline Named pipes Signals Lecture 17
Operating Systems Course Hebrew University Spring 2007 Signals & User Thread.
Home: Phones OFF Please Unix Kernel Parminder Singh Kang Home:
CS4514 Assignment 2 Help Session – Data Link Layer Client and Server Processes Speaker: Hao Shang Date: Nov. 11th, 2004.
Concurrency Sharing of resources in the same time frame Apparent concurrency is sharing the same CPU, memory, or I/O device Real concurrency is sharing.
Signal Signal : - is a notification sent to a process to notify it of some event - interrupts whatever the process is doing and force it to handle a signal.
1 CS4514 – B03 Project 2 Help Session Choong-Soo Lee November 24, 2003.
CSc 352 Signal Handling in Unix Saumya Debray Dept. of Computer Science The University of Arizona, Tucson
Dr. Hugh Melvin, Dept. of IT, NUI,G1 POSIX POSIX: Portable OS Interface –IEEE standard –Mandatory + Optional parts Mostly based on and adopted by Unix.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 26P. 1Winter Quarter Handy Board Lecture.
Week 8 - Friday.  What did we talk about last time?  String to int conversions  Users and groups  Password files.
1 The UNIX date command myclock.cpp example The C/C++ time() and ctime() functions myclock2.cpp example Inline function definitions Inline class member.
Signals & Timers CS241 Discussion Section Spring 2009 Week 6.
4061 Session 17 (3/19). Today Time in UNIX Today’s Objectives Define what is meant when a system is called “interrupt-driven” Describe some trade-offs.
Real-Time Systems Lecture 8 Lärare: Olle Bowallius Telefon: Anders Västberg Telefon:
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo1 Timers and Clocks II.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Real-Time Systems Design1 Priority Inversion When a low-priority task blocks a higher-priority one, a priority inversion is said to occur Assume that priorities:
1 Chapter 2.1 : Processes Process concept Process concept Process scheduling Process scheduling Interprocess communication Interprocess communication Threads.
COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Timers and Clocks.
Time Management.  Time management is concerned with OS facilities and services which measure real time, and is essential to the operation of timesharing.
Process Control Process identifiers Process creation fork and vfork wait and waitpid Race conditions exec functions system function.
System calls for Process management
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 26P. 1Winter Quarter Handy Board Lecture 26.
Thread Implementations; MUTEX Reference on thread implementation –text: Tanenbaum ch. 2.2 Reference on mutual exclusion (MUTEX) –text: Tanenbaum ch
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo1 Timers and Clocks II.
NCHU System & Network Lab Lab #8 Signals Operating System Lab.
1 Signals (continued) CS 241 April 9, 2012 University of Illinois.
Basic I/O in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Stream Model of I/O header file: A stream provides a connection.
UNIX Signals * POSIX-Defined Signals * Signaling Processes * Signal Mask * sigaction * kill and sigaction * alarm * Interval Timers * POSIX.1b Timers *
System Calls & Signals. setsockopt n Used to set socket options n SO_LINGER - Sets or gets the SO_LINGER option. The argument is a linger structure. n.
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo1 Timers and Clocks.
Interacting with Unix. Getting the Process ID u Synopsis #include pid_t getpid(void); u Example: #include int main(){ pid_t n = getpid(); printf("Process.
Lecture 13: Arrays, Pointers, Code examples B Burlingame 2 Dec 2015.
1 Inter Process Communication & Timers. 2 Time.h (page R:Ch9 pp ) #include time_t time(time_t *calptr); Epoch: 00:00 (midnight), Jan 1, 1970 GMT.
1 1 Nov. 24, 2015 Kyu Ho Park Lecture 11 Time Handling,GPIO and I/O Systems.
1/15/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 11 (C-5)
Time Management.  Time management is concerned with OS facilities and services which measure real time.  These services include:  Keeping track of.
S -1 Processes. S -2 wait and waitpid (11.2) Recall from a previous slide: pid_t wait( int *status ) wait() can: (a) block; (b) return with status; (c)
Signals and daemon processes Prepared by : Department of CSE Engineered for Tomorrow Course code: 10CS62.
System calls for Process management Process creation, termination, waiting.
Advanced loop controls. Loop Controls Recall from last week loop controls Event-controlled loops using sentinels repeats until a control variable takes.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Signals.
Week 9 - Wednesday.  What did we talk about last time?  structs.
Advanced Programming in the UNIX Environment Hop Lee.
Computer Science 516 Addressing Modes. Addressing modes are how our programs get to data Multiple addressing modes created for specific uses Function.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
CHAPTER 6. SYSTEM DATA FILES AND INFORMATION System Programming 本份投影片大量參考熊博安教授的系統程式投影片 羅習五 國立中正大學資訊工程學系
Linux/UNIX Programming APUE (Process Control) 문양세 강원대학교 IT 대학 컴퓨터과학전공.
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo
A bit of C programming Lecture 3 Uli Raich.
Time Sources and Timing
Week 9 - Wednesday CS222.
UNIX System Overview.
DATA HANDLING.
Time Sources and Timing
Simulation of Datalink Layer Communication Speaker: Jae Chung
閨怨 ~王昌齡 閨中少婦不知愁, 春日凝妝上翠樓; 忽見陌頭楊柳色, 悔教夫婿覓封侯。.
Presentation transcript:

Timers Timer – Keeps track of the passage of time Simple Timer – Measures elapsed time, reporting it when queried Interval Timer – –Generates an interrupt after a specific time interval –Can cause periodic interrupts (time quantum)

time SYNOPSIS #include time_t time (time_t *tloc); POSIX:CX Returns time in seconds since Epoch If tloc is not NULL, time also stores time in *tloc On error, time returns –1 and sets errno If time_t is 32 bit unsigned long, it would overflow in about 68 years If time_t is 64 bit unsigned long, it would overflow in 292 billion years, long after the sun burned out (after a very long time) Useful in mathematical calculations

difftime SYNOPSIS #include double difftime (time_t time1, time_t time0); POSIX:CX time1 and time0 are calendar times of type time_t

function_to_time void function_to_time(void) { int i; double sum = 0.0; for (i=1;i< ;i++) sum = sum + 1.0/i; printf("The sum is %5.3f\n",sum); } This is the function timed in most of the timing examples that follow

time/difftime example #include void function_to_time(void); int main(void) { time_t tstart; tstart time(NULL); function_to_time(); printf(“function_to_time took %f seconds of elapsed time\n”, difftime(time(NULL), tstart)); return 0; }

ctime Library Function SYNOPSIS #include char *asctime(const struct tm *timeptr); char *ctime(const time_t *clock); struct tm *gmtime(const time_t *timer); struct tm *localtime(const time_t *timer); POSIX:CX ctime converts time to an ASCII string suitable for printing Takes a variable of type time_t and returns a pointer to a 26 character string Uses static storage For example: Sun Oct 06 02:21: \n\0 For thread-safe function add underscore r, ie ctime_r

ctime Example #include int main(void) { time_t tcurrent; tcurrent = time(NULL); printf(“The current time is”, ctime(&tcurrent)); return 0; }

gtime and localtime int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; int tm_wday; int tm_yday; int tm_isdst; seconds after minute (0,60) minutes after hour (0,59) hours since midnight (0,23) day of month (1,31) months since January (0,11) years since 1900 days since Sunday (0,6) days since January 1 (0,365) daylight savings time flag

localtime Example struct tm *tcurrent tcurrent = localtime (time(NULL)); printf(“%d days have elapsed since Jan 1\n”, tcurrent->tm_yday);

gettimeofday SYNOPSIS #include int gettimeofday(struct timeval *tp, void *tzp); POSIX:XSI Handles timings where seconds is too course – returns 0 on success and –1 on error (and sets errno) struct timeval –time_t tv_sec /* seconds since Epoch */ –time_t tv_usec/* and microseconds */ tzp is no longer used – always set it to NULL If a long is 32 bits, max duration is  secs or  35 minutes. This can be extended by using long long (usually 64 bits) – format changes are necessary

#include #include #define MILLION void main(void) { struct timeval tpstart; struct timeval tpend; long timedif; gettimeofday(&tpstart,NULL); function_to_time(); /* timed code goes here */ gettimeofday(&tpend,NULL); timedif = MILLION*(tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec; fprintf(stderr, "It took %ld microseconds\n", timedif ); } gettimeofday - Example

Clocks POSIX Realtime Extension contains clocks A clock is a counter that increments at fixed intervals called the clock resolution

clock_gettime Library Function SYNOPSIS #include int clock_gettime(clockid_t clock_id, struct timespec *tp); int clock_settime(clockid_t clock_id, const struct timespec *tp); int clock_getres(clockid_t clock_id, struct timespec *res); POSIX:TMR These functions return 0 on success and –1 and set errno on failure struct timespec time_t tv_sec /* seconds */ long tv_nsec/* nanoseconds */

/* Example 6.3 */ #include #include #define MILLION void main(void) { struct timespec tpstart; struct timespec tpend; long timedif; clock_gettime(CLOCK_REALTIME, &tpstart); function_to_time(); /* timed code goes here */ clock_gettime(CLOCK_REALTIME, &tpend); timedif = MILLION*(tpend.tv_sec - tpstart.tv_sec) + (tpend.tv_nsec - tpstart.tv_nsec)/1000; fprintf(stderr,"It took %ld microseconds\n", timedif); } clock_gettime – Example

sysconf Library Function SYNOPSIS #include long sysconf(int name); sysconf is used to find the number of ticks per second in a system Example – ticks = double sysconf(_SC_CLK_TCK)

times Library Function SYNOPSIS #include clock_t times (struct tms *buffer); POSIX clock_t holds a number of clock ticks struct tms contains: clock_t tms_utime /* user CPU time of process*/ clock_t tms_stime /* system CPU time on behalf of process */ clock_t tms_cutime /* user CPU time of process and terminated children */ clock_t tms_cstime /* system CPU time on behalf of process and terminated children */ Times returns elapsed time since an arbitrary point in past (or –1 on error and sets errno)

void main(void) { clock_t real_start; clock_t real_end; clock_t ticks_used; struct tms process_start; struct tms process_end; if ((real_start = times(&process_start)) == -1) perror("Could not get starting times"); else { /* perform calculation to be timed */ function_to_time(); if ((real_end = times(&process_end)) == -1) perror("Could not get ending times"); else { ticks_used = process_end.tms_utime + process_end.tms_stime - process_start.tms_utime - process_start.tms_stime; printf("Fraction of time running = %f\n", (double)(ticks_used)/(real_end - real_start)); } } } times - Example

sleep SYNOPSIS #include unsigned sleep(unsigned seconds); POSIX Sleep blocks for the number of seconds specified It could be implemented with an interval timer

nanosleep SYNOPSIS #include int nanosleep(const struct timespec *rqtp, struct timespec *rmtp); POSIX:TMR Causes the calling thread to suspend execution until the time interval specified by rqtp has elapsed or signal is received If interrupted by signal and rmtp is not NULL, location pointed to by rmtp contains time remaining allowing nanosleep to be restarted The system clock CLOCK_REALTIME determines resolution of rqtp

Interval Timers POSIX:XSI –Gives each process a small fixed number of timers –One of each of the types ITIMER_REAL ITIMER_VIRTUAL ITIMER_PROF POSIX:TMR –Takes an alternative approach where there are a small number of clocks, such as CLOCK_REALTIME –A process can create many independent timers for each clock

POSIX:XSI Interval Timers ITIMER_REAL:decrements in real time and generates a SIGALRM signal when it expires ITIMER_VIRTUAL:decrements in virtual time (time used by the process) and generates a SIGVTARM signal when it expires ITIMER_PROFdecrements in virtual time and system time for the process and generates a SIGPROF signal when it expires

struct itimerval it_value /* time until next expiration */ it_interval /* value to reload into timer */

setitimer SYNOPSIS #include int setitimer (int which, const struct itimerval *value, struct itimerval *ovalue); POSIX:XSI

ITIMER_PROF - Example (top) #include #include #include #include #include char astbuf[] = "*"; static void myhandler(int s) { write(STDERR_FILENO, astbuf, sizeof(char)); } /* set up the myhandler handler for signal SIGPROF */ void init_timer_interrupt(void) { struct sigaction newact; newact.sa_handler = myhandler; newact.sa_flags = SA_RESTART; sigemptyset(&newact.sa_mask); sigaction(SIGPROF, &newact, NULL); }

/* set the ITIMER_PROF interval timer for 2-second intervals */ void setup_interval_timer(void) { struct itimerval value; value.it_interval.tv_sec = 2; value.it_interval.tv_usec = 0; value.it_value = value.it_interval; setitimer(ITIMER_PROF, &value, NULL); } void main(void) { init_timer_interrupt(); setup_interval_timer(); /* execute rest of main program here */ function_to_time(); exit(0); } ITIMER_PROF – Example (bottom)

getitimer SYNOPSIS #include int getitimer (int which, struct itimerval *value); POSIX:XSI Use getitimer to determine the amount of time remaining on a POSIX:XSI interval timer getitimer sets the *value structure with the time remaining until the which timer expires getitimer returns 0 on success and returns –1 and sets errno on failure

POSIX:XSI Interval Timer to Time Code #include #include #define MILLION void main(void) { struct itimerval value; struct itimerval ovalue; long timedif; value.it_interval.tv_sec = 0; value.it_interval.tv_usec = 0; value.it_value.tv_sec = MILLION; /* a large number */ value.it_value.tv_usec = 0; setitimer(ITIMER_VIRTUAL, &value, NULL); getitimer(ITIMER_VIRTUAL, &ovalue); function_to_time(); /* timed code goes here */ getitimer(ITIMER_VIRTUAL, &value); timedif = MILLION*(ovalue.it_value.tv_sec – value.it_value.tv_sec) + ovalue.it_value.tv_usec - value.it_value.tv_usec; printf("It took %ld microseconds\n", timedif); }

POSIX.TMR Interval Timers POSIX.TMR interval timers are per- process timers not inherited on a fork POSIX.TMR timers are based on the itimerspec structure with the following members: it_interval /* timer period */ it_value /* timer expiration */

timer_create SYNOPSIS #include int timer_create(clockid_t clock_id, struct sigevent *evp, timer_t *timerid); struct sigevent { intsigev_notify/* notification type */ intsigev_signo;/* signal number */ union sigvalsigev_value;/* signal value */ }; union sigval { intsival_int;/* integer value */ void*sival_ptr/* pointer value */ }; timer_create returns 0 on success or –1 and sets errno on error

timer_create parameters clock_id specifies the clock the timer is based on *timerid holds the ID of the created timer sigevent structure and sigval union are required by POSIX.1b but there may be additional parameters *evp specifies signal to be sent – for CLOCK_REALTIME the default is SIGALRM The evp->sigev_notify member indicates action to be taken on timer expiration If evp->sigev_notify is set to SIGEV_NONE, no signal is sent If several timers generate the same signal, evp- >sigev_value is used to distinguish which timer generated the signal – Use SA_SIGINFO flag in sa_flags member of struct sigaction to do this

POSIX.TMR Interval Timer Operations SYNOPSIS #include int timer_settime(timer_t timerid, int flags, const struct itimerspec *value, struct itimerspec *ovalue); int timer_gettime(timer_t timerid, struct itimerspec *value); int timer_getoverrun(timer_t timerid);

timer_settime Starts or stops a timer created by calling timer_create flags parameter indicates whether timer uses relative or absolute time – relative time is similar to Spec 1170 timers while absolute time allows for greater accuracy and control of timer drift value and ovalue parameters have same meaning as for setitimer

timer_gettime Gets the time remaining on an active timer It is possible for timer to expire while a signal is still pending from a previous expiration of the same timer – signals may be lost (called timer overrun) Timer overruns occur only in signals generated by the same timer

POSIX.TMR Interval Timer to Time Code (top) /* Program 6.3 */ #include #include #include #include #define MILLION #define THOUSAND 1000 void main(void) { timer_t time_ID; struct itimerspec value; struct itimerspec ovalue; long timedif;

POSIX.TMR Interval Timer to Time Code (bottom) if (timer_create(CLOCK_REALTIME, NULL, &time_ID) < 0) { perror("Could not create a timer based on CLOCK_REALTIME"); exit(1); } value.it_interval.tv_sec = 0; value.it_interval.tv_nsec = 0; value.it_value.tv_sec = MILLION; /* a large number */ value.it_value.tv_nsec = 0; timer_settime(time_ID, 0, &value, NULL); timer_gettime(time_ID, &ovalue); function_to_time(); /* timed code goes here */ timer_gettime(time_ID, &value); timedif = MILLION*(ovalue.it_value.tv_sec value.it_value.tv_sec) + (ovalue.it_value.tv_nsec - value.it_value.tv_nsec)/THOUSAND; printf("It took %ld microseconds\n", timedif ); }