Sei sulla pagina 1di 68

Time, Timers and Signals

EEE 13

Applications of Times and


Timers

Process scheduling

Timeouts

network protocols

User input

Periodic updates and system statistics

Event management

POSIX Time

POSIX specifcation

Time in terms of seconds since Epoch

1 day = 86,400 secs

Epoch

00:00 (midnight), January 1, 1970

Coordinated Universal Time (UTC or


Greenwich Mean Time GMT)

POSIX Extensions

POSIX:XSI Extension

microseconds resolution

POSIX:TMR

nanoseconds resolution

Time Since Epoch


NAME
time - get time in seconds
RETURN
time in seconds since epoch
SYNOPSIS
#include <time.h>
time_t time(time_t *t);
PARAMETER
time is also stored in *t if t
is not NULL
5

Notes on time

time_t

time resolution in seconds

usually as big as long data type

How long does it take for time_t to


overfow?

32-bit =>

Signed = 2 billion seconds from 1970

(2038)

Unsigned = 4 billion seconds from 1970 (2106)

64-bit => much much longer


6

Time Diference
NAME
difftime - calculate time difference
RETURN

time difference in seconds


SYNOPSIS
#include <time.h>
double difftime(time_t time1,
time_t time0);
7

diftime() sample
#include <stdio.h>
#include <time.h>
int main (void)
{
time_t t0;
int
i = 7;
int
y;
t0 = time(NULL);
while (i > 0) {
i--;
y = 0xFFFFFFF;
while (y > 0)
y--;
}
printf("Executed in %lf seconds.\n", diftime(time(NULL), t0));
return 0;
}

Date and Time


NAME
ctime, gmtime, localtime, mktime, asctime
transform date and time to broken-down
time or ASCII
SYNOPSIS
#include <time.h>
char

*ctime(const time_t *timep);

struct tm

*gmtime(const time_t *timep);

struct tm

*localtime(const time_t *timep);

char

*asctime(const struct tm *tm);

time_t

mktime(struct tm *tm);
9

struct tm
struct tm {
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 */
minutes */
hours */
day of the month */
month */
year */
day of the week */
day in the year */
daylight saving time */

10

Date and Time

gmtime()

converts the calendar time timep to


broken-down time representation,

expressed in Coordinated Universal Time


(UTC)

localtime()

converts the calendar time timep to


broken-time representation

expressed relative to the user's


specifed time zone.

11

localtime()
#include <stdio.h>
#include <time.h>
int main (void)
{
struct tm
time_t

*current;
t = time(NULL);

current = localtime(&t);
printf ("%d days before Xmas\n",
359 - current->tm_yday);
return 0;
}

12

Date and Time

asctime()

Converts broken-down time into string

It converts the calendar time_t into a


string of the form
"Wed Jun 30 21:49:08 1993\n"

mktime()

Converts broken-down time into time_t

13

asctime()
#include <stdio.h>
#include <time.h>
int main (void)
{
time_t
t0;
t0 = time (NULL);
printf ("%s", asctime(localtime(&t0)));
/* Mon Aug 4 13:20:25 2008 */
}

return 0;
14

Date and Time

ctime()

Function call takes an argument of data


type time_t

Equivalent to asctime(localtime(t))

It converts the calendar time_t into a


string of the form
"Wed Jun 30 21:49:08 1993\n"
Uses a static variable to store converted
time in string format

15

ctime()
#include <stdio.h>
#include <time.h>
int main (void)
{
time_t
t0;
t0 = time (NULL);
printf ("%s",ctime(&t0));
/* Mon Aug 4 13:20:25 2008 */
}

return 0;
16

Time functions
asctime

localtime
struct tm

seconds
time

string

gmtime
mktime
ctime

seconds

string
17

Thread-safe Versions
NAME
asctime_r, ctime_r, gmtime_r, localtime_r
transform date and time to broken-down
time or ASCII without using static
variables
SYNOPSIS
#include <time.h>
char *asctime_r(const struct tm *tm,char *buf);
char *ctime_r(const time_t *timep, char *buf);
struct tm *gmtime_r(const time_t *timep, struct
tm *result);
struct tm *localtime_r(const time_t *timep,
struct tm *result);
18

Timer w/ Finer Scale


NAME
gettimeofday, settimeofday
get / set time
SYNOPSIS
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct
timezone *tz);
int settimeofday(const struct timeval *tv ,
const struct timezone *tz);

19

struct timeval
struct timeval {
long tv_sec;
long tv_usec;

/* seconds */
/* microseconds */

};

tv_sec and tv_usec

Seconds and micro seconds since Epoch

20

struct timezone
struct timezone {
int

tz_minuteswest;

/* minutes W of Greenwich */
int tz_dsttime;
/* type of dst correction */
};

timezone is usually set to NULL or 0

21

gettimeofday()
#include <stdio.h>
#include <sys/time.h>
int main (void)
{
int i, y;
struct timeval t0,t1;
gettimeofday(&t0,0);
i = 3;
while (i > 0) {
i--;
y = 0xFFFFFFF;
while(y > 0)
y--;
}
gettimeofday(&t1,0);
printf ("%lu usecs elapsed \n",
1000000*(t1.tv_sec-t0.tv_sec)
+ t1.tv_usec-t0.tv_usec);
return 0;
}

22

Real-time Clocks
clock_id = CLOCK_REALTIME
#include <time.h>

int clock_gettime (clockid_t clock_id,


struct timespec *tp)
Get current value of clock CLOCK_ID and store
it in tp
int clock_settime (clockid_t clock_id, const
struct timespec *tp)

Set clock CLOCK_ID to value tp


int clock_getres (clockid_t clock_id, struct
timespec *res)

Get resolution of clock CLOCK_ID


23

struct timespec
struct timespec{
time_t tv_sec;

/*Seconds. */

long int tv_nsec; /*Nanoseconds. */


};

Like `struct timeval' but in nanoseconds


instead of microseconds

24

gettime()
#include <stdio.h>
#include <time.h>
int main (void)
{
int i = 0;
struct timespec t0,t1;

clock_gettime(CLOCK_REALTIME, &t0);
i = 0xFFFFFF;
while (i > 0)
i--;
clock_gettime(CLOCK_REALTIME, &t1);
printf ("%lu nsecs elapsed \n",
1000000000*(t1.tv_sec-t0.tv_sec)
+t1.tv_nsec-t0.tv_nsec);
return 0;
25

Delaying Functions
NAME
sleep
sleep for the specified number of
seconds
SYNOPSIS
#include <unistd.h>
unsigned int sleep(unsigned int seconds);

26

sleep() sample
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main (void)
{
time_t t0;
t0 = time(NULL);

/* Better than loop */


sleep(2);
printf("Executed in %lf seconds.\n", diftime(time(NULL), t0));
return 0;
}

27

Delaying Functions
NAME
nanosleep
pause execution for a specified time
SYNOPSIS
#include <time.h>
int nanosleep(const struct timespec *req,
struct timespec *rem);

nanosleep delays the execution of the program


for at least the time specifed in *req.
Remaining time stored in *rem

e.g. on error

28

Function Pointers

29

Functions occupy memory

Functions have addresses

Function name is like a variable

Mapped to a memory location

We can use these addresses to


refer/use a particular function

Simplify coding

Makes program more dynamic/fexible

30

Syntax

Declaration:
<return type> (* variable) (parameters);

variable that can be assigned an


address of a function

same return type and parameters

Examples:
int (* funcptr)(int a, int b);
int (* funcptr)(int, int);
int (* mypointer)(int a, int b);

Parameter names are optional

31

#include <stdio.h>
int test1(int k)
{
return k;
}
int test2(int k)
{
return 2*k;
}
int main(void)
{
int (*funcptr)(int a);
/* Strict form */
funcptr = &test1;
printf ("%d\n", (*funcptr)(10));

/* 10 */

/* Short form */
funcptr = test2;
printf ("%d\n", funcptr(10));

/* 20 */

return 0;
}

/* Function pointer */

32

Function Pointer, is a Pointer

Same rules to pointers apply


Don't use, without assigning a proper
address

33

#include <stdio.h>
int getsum(int k, int l)
{
return k+l;
}
int getproduct(int k, int l)
{
return k*l;
}
/* 3rd parameter is function pointer */
void processnumbers (int num1, int num2, int (*funcptr)(int, int))
{
printf("%d\n", funcptr(num1, num2));
}
int main(void)
{
processnumbers(10, 20, getsum);
processnumbers(10, 20, getproduct);
return 0;
}

/* 30 */
/* 200 */

34

#include <stdio.h>
typedef foat (*funcptr)(foat, foat); /* funcptr is now a data type */
foat getsum(foat k, foat l)
{
return k+l;
}
foat getproduct(foat k, foat l)
{
return k*l;
}
int main(void)
{
funcptr a;
a = getsum;
printf("%f\n", a(6, 2));

/* 8.00 */

a = getproduct;
printf("%f\n", a(6, 2));

/* 12.00 */

return 0;
}

35

#include <stdio.h>
typedef foat (*funcptr)(foat, foat);

/* funcptr is now a data type */

foat getsum(foat k, foat l)


{
return k+l;
}
foat getproduct(foat k, foat l)
{
return k*l;
}
foat getquotient(foat k, foat l)
{
return k/l;
}
int main(void)
{
int i = 0;
funcptr var[3] = {
getsum, getproduct, getquotient
};
while (i < 3) {
printf("%f\n", var[i](6, 2));
i++;
}
return 0;
}

36

Signal

37

Signal

Signals are software interrupts


Signals provide a handling mechanism
to handle asynchronous events

38

Signal Illustration
Process
Register
signal handler

Kernel calls
signal handler
when even occurs

Runs in
parallel

39

Signal Names

SIGABRT

SIGALRM

Generated when an alarm expires

SIGBUS

Generated by function abort()

Generated by implementation defned


hardware fault

SIGFPE

Generated by arithmetic exception (e.g. 1/0)


40

Signal Names / IDs

SIGCHLD

SIGHUP

Signal sent to a controlling process

SIGINT

Generated when a process terminates

Generated by interrupt key (eg Ctl-C)

SIGIO

Generated by asynchronous I/O event


41

Signal Names / IDs

SIGSEGV

SIGURG

Generated to notify a process that an


urgent condition occurred

SIGUSR1 & SIGUSR2

Generated when a process made an


invalid memory reference

User defned signal

See asm/signal.h for more info


42

signal()
NAME
signal - ANSI C signal handling
SYNOPSIS
#include <signal.h>
sighandler_t signal(int signum,
sighandler_t handler);

43

signal() Syntax

signum

Any signal name/id, except SIGKILL and


SIGSTOP

handler

Can be one of the following:

SIG_IGN

SIG_DFL

Ignore the signal


Use default action (ignore, terminate or stop)

Name of function to handle the signal (function


pointer)

typedef void (*sighandler_t)(int);


44

signal() Return Value

signum if success

SIG_ERR if error

Note:

Use of sigaction() is recommended over


signal()

45

Related Functions

pause()

Suspends the calling process until a signal


is caught

Signal must be one of those monitored by


the calling process

46

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
void sig_usr(int signo){
if(signo==SIGINT)
printf("Got SIGINT\n");
else
printf("Unknown signal number\n");
}
int main(void)
{
if( signal(SIGINT, sig_usr) == SIG_ERR ) {
printf("Error creating SIG_INT\n");
return 1;
}
while(1)
pause();
return 0;
} /* Run program and use CTRL+C */

47

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
void sig_usr(int signo){
if(signo==SIGUSR1)
printf("Got SIGUSR1\n");
else
printf("Unknown signal number\n");
}
int main(void)
{
if( signal(SIGUSR1, sig_usr) == SIG_ERR ) {
printf("Error creating SIGUSR1\n");
return 1;
}
while(1)
pause();
return 0;
} /* Run program and use kill -USR1 to signal */

48

sigaction()
NAME
sigaction
POSIX signal handling function.
SYNOPSIS
#include <signal.h>
int sigaction(int signum,
const struct sigaction *act,
struct sigaction *oldact)

System call used to change the action taken by


a process on receipt of a specifc signal
49

sigaction()

signum

act

Any signal name/id, except SIGKILL and


SIGSTOP
the new action for signal signum

oldact

If non-null, the previous action is saved in


oldact.

Useful when you want to restore


50

struct sigaction
struct sigaction {
void (*sa_handler)(int);
void (*sa_sigaction)(int , siginfo_t *, void *);
sigset_t
sa_mask;
int
sa_fags;
void (*sa_restorer)(void);
};

sa_handler

Same as in signal()
sa_mask

mask of signals which should be blocked


during execution of the signal handler.
sa_flags

See man sigaction() for details

sa_restorer is obsolete/unused

51

siginfo_t
siginfo_t {
int
si_signo; /* Signal number */
int
si_errno; /* An errno value */
int
si_code; /* Signal code */
pid_t si_pid; /* Sending process ID */
uid_t si_uid; /* Real user ID of sending process */
int
si_status; /* Exit value or signal */
clock_t si_utime; /* User time consumed */
clock_t si_stime; /* System time consumed */
sigval_t si_value; /* Signal value */
int
si_int; /* POSIX.1b signal */
void * si_ptr; /* POSIX.1b signal */
void * si_addr; /* Memory location which caused fault */
int
si_band; /* Band event */
int
si_fd;
/* File descriptor */
};

52

sigaction() Return Value

success

-1

error

53

siemptyset()
NAME
sigemptyset
POSIX signal set operation.
SYNOPSIS
#include <signal.h>
int sigemptyset(sigset_t *set);

Initializes the signal set given by set to


empty, with all signals excluded from the
set.
54

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
void sig_usr(int signo){
if(signo==SIGINT)
printf("Got SIGINT\n");
else
printf("Unknown signal number\n");
}
int main(void)
{
struct sigaction sa;
sa.sa_handler = sig_usr;
sigemptyset(&sa.sa_mask);
sa.sa_fags = 0;
if(sigaction(SIGINT, &sa, NULL) == -1) {
printf("Error creating SIG_INT\n");
return 1;
}
while(1)
pause();
return 0;
}
/* Run program and use CTRL+C */

55

Related Functions

kill()

Sends signal to a process or group of


processes

raise()

Sends signal to itself

56

kill()
#include
#include
#include
#include

<sys/types.h>
<unistd.h>
<signal.h>
<stdio.h>

void childprocess(char *buf)


{
int counter = 0;
while(1) {
printf("Message %d: %s\n", counter, buf);
counter++;
sleep(2);
}
}
57

int main(void)
{
pid_t
id; /* Holds PID of current child */
int
number;
id = fork();
if (id == 0) {
childprocess("Enter a number");
return 0;
}
/* Parent process */
while(1) {
scanf("%d", &number);
if (number == 123)
break;
printf("Try again\n");
}
kill(id, SIGUSR1); /* terminate repeating message */
printf("Finally!\n");
return 0;
}
/* main */

58

Related Functions

alarm()

Generate SIGALRM at a specifed time in


the future

59

alarm()
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void sig_alarm(int signo)
{
if(signo==SIGALRM) {
printf("Got SIGALRM\n");
alarm(10);
printf("Will generate alarm in 10 secs\n");
} else {
printf("Unknown signal number\n");
}
}
60

alarm()
int main(void)
{
struct sigaction act;
act.sa_handler = sig_alarm;
act.sa_fags = 0;
sigemptyset(&act.sa_mask);
if (sigaction (SIGALRM, &act, 0) == -1) {
perror (NULL);
return 1;
}
alarm (10);
printf ("Will generate alarm in 10 secs\n");
while(1)
pause();
return 0;
}
61

Interval Timers
NAME
getitimer, setitimer
get or set value of an interval timer
SYNOPSIS
#include <sys/time.h>
int getitimer(int which,
struct itimerval *value);
int setitimer(int which,
const struct itimerval *value,
struct itimerval *ovalue);
62

struct itimerval
struct itimerval {
struct timeval it_interval; /* next value */
struct timeval it_value; /* current value */
};

63

which parameter

ITIMER_REAL

ITIMER_VIRTUAL

decrements in real time, and delivers SIGALRM


upon expiration.
decrements only when the process is executing,
and delivers SIGVTALRM upon expiration.

ITIMER_PROF

decrements both when the process executes and


when the system is executing on behalf of the
process.

usually used to profle the time spent by the


application in user and kernel space. SIGPROF is
delivered upon expiration.
64

Interval Timers

getitimer()

flls the structure with the current setting


for the timer indicated by which

ITIMER_REAL,
ITIMER_PROF

ITIMER_VIRTUAL, or

setitimer()

sets the indicated timer to the value in


value.

If ovalue is nonzero, the old value of the


timer is stored there.
65

Interval Timers
#include<stdio.h>
#include<signal.h>
#include<time.h>
#include<unistd.h>
#include<sys/time.h>
void myalarm(int signum)
{
if (signum == SIGALRM ) {
printf("Alarm\n");
signal ( SIGALRM, myalarm);
}
}
66

Interval Timers

int main(void)
{
struct itimerval timer;

signal (SIGALRM, myalarm);


/* initial interval */
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 100000;
/* subsequent intervals */
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 50000;
setitimer(ITIMER_REAL, &timer, NULL);
while(1)
pause();
return 0;
}

67

End

68

Potrebbero piacerti anche