Writing a Pong Game ● screen control ● tty control ● time ● asynchronous program.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

Linux Serial Programming for POSIX Operating Systems
Using our device-drivers How can an application display the data in a device special file?
Real-Time Library: RTX
An Introduction to C Adam Gleitman – IAP 2014.
Chapter 14 - Advanced C Topics Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 14 - Advanced C Topics Outline 14.1Introduction.
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.
Daemon Processes Long lived utility processes Often started at system boot and ended when system shuts down Run in the background with no controlling terminal.
Interrupts What is an interrupt? What does an interrupt do to the “flow of control” Interrupts used to overlap computation & I/O – Examples would be console.
Exec function Exec function: - replaces the current process (its code, data, stack & heap segments) with a new program - the new program starts executing.
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.
CHAPTER 6 FILE PROCESSING. 2 Introduction  The most convenient way to process involving large data sets is to store them into a file for later processing.
Linux game programming An introduction to the use of interval timers and asynchronous input notifications.
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.
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo1 Timers and Clocks II.
1Reference “Introduction To Unix Signals Programming” in the reference material section Man page – sigprocmask, alarm “Understanding the Linux Kernel”
TELE 402 Lecture 4: I/O multi … 1 Overview Last Lecture –TCP socket and Client-Server example –Source: Chapters 4&5 of Stevens’ book This Lecture –I/O.
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.
1 I/O Multiplexing We often need to be able to monitor multiple descriptors:We often need to be able to monitor multiple descriptors: –a generic TCP client.
CSCE 515: Computer Network Programming Select Wenyuan Xu Department of Computer Science and Engineering.
I/O Multiplexing. What is I/O multiplexing? When an application needs to handle multiple I/O descriptors at the same time –E.g. file and socket descriptors,
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo1 Timers and Clocks II.
PA3: Improving Performance with I/O Multiplexing Part 1-1: Nov. 7, Part 1-2: Nov. 10 Part 2-1: Nov. 17, Part 2-2: Nov.20.
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)
1 Lecture 19: Unix signals and Terminal management n what is a signal n signal handling u kernel u user n signal generation n signal example usage n terminal.
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
1 4-Integrating Peripherals in Embedded Systems. 2 Introduction Single-purpose processors  Performs specific computation task  Custom single-purpose.
1 Computer System Overview Chapter 1. 2 Operating System Exploits the hardware resources of one or more processors Provides a set of services to system.
Introduction Every program takes some data as input and generate processed data as out put . It is important to know how to provide the input data and.
Libraries.
Error handling I/O Man pages
C++ Lesson 1.
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Informatica PowerCenter Performance Tuning Tips
Protection of System Resources
Loop Structures.
Using Processes.
UNIX PROCESSES.
Tarek Abdelzaher Vikram Adve Marco Caccamo
Interrupt.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Topics Introduction to File Input and Output
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Introduction to C++ Programming
Chapter 14 - Advanced C Topics
CSC Advanced Unix Programming, Fall 2015
Module 2: Computer-System Structures
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Govt. Polytechnic,Dhangar
Introduction C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell.
Md. Mojahidul Islam Lecturer Dept. of Computer Science & Engineering
Md. Mojahidul Islam Lecturer Dept. of Computer Science & Engineering
CSE 333 – Section 3 POSIX I/O Functions.
C Programming Getting started Variables Basic C operators Conditionals
Interrupt handling Explain how interrupts are used to obtain processor time and how processing of interrupted jobs may later be resumed, (typical.
Computer System Overview
I/O Multiplexing We often need to be able to monitor multiple descriptors: a generic TCP client (like telnet) need to be able to handle unexpected situations,
Module 2: Computer-System Structures
Topics Introduction to File Input and Output
Module 2: Computer-System Structures
Week 10 FILE PROCESSING.
Chapter 13: I/O Systems “The two main jobs of a computer are I/O and [CPU] processing. In many cases, the main job is I/O, and the [CPU] processing is.
Presentation transcript:

Writing a Pong Game ● screen control ● tty control ● time ● asynchronous program

Programming Issues ● Writing to any position on the screen ● Writing at the correct time ● Asynchronous user input and video action

Curses Library ● The curses library is a set of functions that allows a programmer to position the cursor and control the appearance of the text on the terminal screen

Curses Library ● Useful curses functions: – initscr() – refresh() – endwin() – move(row,col) – addstr(str) – addch(c) – clear() – standout(), standend()

Using Curses ● hello1.c /* hello1.c * purpose show the minimal calls needed to use curses * outline initialize, draw stuff, wait for input, quit */ #include main() { initscr() ; /* turn on curses */ /* send requests */ clear(); /* clear screen */ move(10,20); /* row10,col20 */ addstr("Hello, world"); /* add a string */ move(LINES-1,0); /* move to LL */ refresh(); /* update the screen */ getch(); /* wait for user input */ endwin(); /* turn off curses */ }

hello2.c #include main(){ inti; initscr(); /* part2 : do some screen operations*/ clear(); for(i=0; i<LINES; i++ ){ move( i, i+i ); if ( i%2 == 1 ) standout(); addstr("Hello, world"); if ( i%2 == 1 ) standend(); } /* part3 : push requests to screen*/ refresh(); getch(); /* part4 : wrapup*/ endwin();}

hello3.c #include main() { inti; initscr(); /* do some screen operations*/ clear(); for(i=0; i<LINES; i++ ){ move( i, i+i ); if ( i%2 == 1 ) standout(); addstr("Hello, world"); if ( i%2 == 1 ) standend(); sleep(1); refresh();} /* wrapup*/ endwin(); }

Hello4.c #include main() [ inti; initscr(); /* do some screen operations*/ clear(); for(i=0; i<LINES; i++ ){ move( i, i+i ); if ( i%2 == 1 ) standout(); addstr("Hello, world"); if ( i%2 == 1 ) standend(); refresh(); sleep(1); move(i,i+i);/* move back */ addstr(" ");/* erase line*/} endwin();}

Hello5.c #include #defineLEFTEDGE10 #defineRIGHTEDGE30 #defineROW10 main() { charmsg[] = " Hello ";/* notice padding spaces */ intdir = +1; intpos = LEFTEDGE ; initscr();clear(); while(1){ move(ROW,pos);addstr( msg );/* draw it */ move(LINES-1,COLS-1);/* park the cursor*/ refresh();pos += dir;/* advance position*/ if ( pos >= RIGHTEDGE )/* check for bounce*/ dir = -1; if ( pos <= LEFTEDGE ) dir = +1; sleep(1);}}

setitimer() NAME getitimer, setitimer - get or set value of an interval timer SYNOPSIS #include int getitimer(int which, struct itimerval *value); int setitimer(int which, const struct itimerval *value, struct itimer- val *ovalue); DESCRIPTION The system provides each process with three interval timers, each decrementing in a distinct time domain. When any timer expires, a signal is sent to the process, and the timer (potentially) restarts. ITIMER_REAL decrements in real time, and delivers SIGALRM upon expiration. ITIMER_VIRTUAL 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. Coupled with ITIMER_VITUAL, this timer is usually used to profile the time spent by the application in user and kernal space. SIGPROF is delivered upon expiration.

Setitimer() Timer values are defined by the following structures: struct itimerval { struct timeval it_interval; /* next value */ struct timeval it_value; /* current value */ }; struct timeval { long tv_sec; /* seconds */ long tv_usec; /* microseconds */ };

setitimer() Setitimer offer two improvements over alarm: 1) resolution in milliseconds or better 2) pulsing, rather than one shot timers() The function getitimer fills the structure indicated by value with the current setting for the timer indicated by which (one of ITIMER_REAL, ITIMER_VIRTUAL, or ITIMER_PROF). The element it_value is set to the amount of time remaining on the timer, or zero if the timer is dis- abled. Similarly, it_interval is set to the reset value. The func- tion setitimer sets the indicated timer to the value in value. If ovalue is nonzero, the old value of the timer is stored there.

setitimer() Timers decrement from it_value to zero, generate a signal, and reset to it_interval. A timer which is set to zero (it_value is zero or the timer expires and it_interval is zero) stops. Both tv_sec and tv_usec are significant in determining the duration of a timer. Timers will never expire before the requested time, instead expiring some short, constant time afterwards, dependent on the system timer resolution (currently 10ms). Upon expiration, a signal will be gener- ated and the timer reset. If the timer expires while the process is active (always true for ITIMER_VIRT) the signal will be delivered immediately when generated. Otherwise the delivery will be offset by a small time dependent on the system loading.

usleep USLEEP(3) Linux Programmer's Manual USLEEP(3) NAME usleep - suspend execution for microsecond intervals SYNOPSIS #include void usleep(unsigned long usec);

Reentrant Code A signal handler or and system function that can be called when it is already active without causing a problem is called reentrant. Typically functions that use static (ie global) storage locations for routine variables are not reentrant.

curses=ncurses ● No man page for crmode() but it works in program. ● Look in /usr/include/curses.h #define crmode() cbreak() #define nocrmode() nocbreak() man cbreak gives: curs_inopts(3X) NAME cbreak, nocbreak, echo, noecho, halfdelay, intrflush, keypad, meta, nodelay, notimeout, raw, noraw, noqiflush, qiflush, timeout, wtimeout, typeahead - curses input options

cbreak Normally, the tty driver buffers typed characters until a newline or carriage return is typed. The cbreak routine disables line buffering and erase/kill character-processing (interrupt and flow control charac- ters are unaffected), making characters typed by the user immediately available to the program. The nocbreak routine returns the terminal to normal (cooked) mode. Initially the terminal may or may not be in cbreak mode, as the mode is inherited; therefore, a program should call cbreak or nocbreak explic- itly. Most interactive programs using curses set the cbreak mode. Note that cbreak overrides raw. [See curs_getch(3X) for a discussion of how these routines interact with echo and noecho.]

Bounce1d.c ● See Bounce1d.c on class web page – can multiple signals cause a problem? – can we make it reentrant?

Bounce2d.c struct ppball { int y_pos, x_pos, /* ball position*/ y_ttm, x_ttm, /* x,y interrupts per move */ y_ttg, x_ttg, /* x,y interrupt count */ y_dir, x_dir; /* x,y direction to move */ char symbol ; } ;

O_ASYNC Generate a signal (SIGIO by default, but this can be changed via fcntl(2)) when input or output becomes possible on this file descriptor. This feature is only available for terminals, pseudo-terminals, and sockets. See fcntl(2) for further details.

Bounce_async.c The main loop here is while (1) pause. Is there another way to set this up?

Exercise ● Reaction-Time Tester. Write a program that measures how quickly a user can respond. The program waits for a random interval of time then prints a single digit on the screen. The user has to type that digit as quickly as possible. The program records how long it takes the user to respond. Your program should perform 10 such tests and report the minimum, maximum and average response time. (Hint, read the manual page for gettimeofday).

aio_read() NAME aio_read - asynchronous read SYNOPSIS #include int aio_read(struct aiocb *aiocbp); DESCRIPTION The aio_read function requests an asynchronous "n = read(fd, bu count)" with fd, buf, count given by aiocbp->aio_filde aiocbp->aio_buf, aiocbp->aio_nbytes, respectively. The return status can be retrieved upon completion using aio_return(3). The data is read starting at the absolute file offset aiocbp->aio_of set, regardless of the current file position. After this request, t value of the current file position is unspecified. The "asynchronous" means that this call returns as soon as the request has been enqueued; the read may or may not have completed when the call returns. One tests for completion using aio_error(3).

aio.h s truct aiocb {int aio_fildes; /* File desriptor. */ int aio_lio_opcode; /* Operation to be performed. */ int aio_reqprio; /* Request priority offset. */ volatile void *aio_buf; /* Location of buffer. */ size_t aio_nbytes; /* Length of transfer. */ struct sigevent aio_sigevent; /* Signal number and value. */ /* Internal members. */ struct aiocb *__next_prio; int __abs_prio; int __policy; int __error_code; __ssize_t __return_value; #ifndef __USE_FILE_OFFSET64 __off_t aio_offset; /* File offset. */ char __pad[sizeof (__off64_t) - sizeof (__off_t)]; #else __off64_t aio_offset; /* File offset. */ #endif char __unused[32]; };