SlideShare a Scribd company logo
UNIX Systems Programming I
Short Course Notes
Alan Dix © 1996
http://www.hcibook.com/alan/
UNIXSystems
Programming I
UNIXSystems
Programming I
UNIXSystems
Programming I
UNIXSystems
Programming I
UNIXSystems
Programming I
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/i
UNIXSystems
Programming I
Course
Outline
Alan Dix
http://www.hcibook.com/alan/
Session 1 UNIX basics the UNIX API, system calls
and manuals
Session 2 file I/O and filters standard input and output, read,
write and open
Session 3 makefiles and
arguments
make, argc & argv and
environment variables
Session 4 file manipulation creating and deleting files and
directories, links and symbolic
links
Session 5 terminal I/O similarities to file I/O, ttyÊdrivers,
stty & gtty, termcap and curses
Session 6 signals and time catching signals and problems
that arise, delays and finding the
time
Session 7 mixing C and scripts shell scripts, getting information
between C and shell, putting
them together
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/ii
UNIXSystems
Programming I Reading
¥ The Unix V Environment,
Stephen R. Bourne,
Wiley, 1987, ISBN 0 201 18484 2
The author of the Borne Shell! A 'classic' which deals with system
calls, the shell and other aspects of UNIX.
¥ Unix For Programmers and Users,
Graham Glass,
Prentice-Hall, 1993, ISBN 0 13 061771 7
Slightly more recent book also covering shell and C programming.
Ì BEWARE Ð UNIX systems differ in details,
check on-line documentation
¥ UNIX manual pages:
man creat etc.
Most of the system calls and functions are in section 2 and 3 of the
manual. The pages are useful once you get used to reading them!
¥ The include files themselves
/usr/include/time.h etc.
Takes even more getting used to, but the ultimate reference to
structures and definitions on your system.
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/1
UNIXSystems
Programming I
Session 1
UNIX basics
¥ the nature of UNIX
¥ the UNIX API
¥ system calls and library calls
¥ system call conventions
¥ how they work
¥ UNIX manuals and other info
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/2
UNIX
UNIX is an operating system
file store programsnetworks etc.
UNIX
It manages:
¥ files and data
¥ running programs
¥ networks and other resources
It is defined by
¥ its behaviour (on files etc.)
¥ its application programmers interface Ð API
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/3
UNIX API – the system calls
¥ ultimately everything works through system calls
shell
file store programsnetworks etc.
UNIX
API
system
daemons
user
applications X
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/4
first system call – exit
void exit(int status)
¥ program ends!
¥ its exit code is set to status
¥ available to shell:
$? Ð Bourne shell
$status Ð C shell
¥ actually not a real system call!
r does some tidying up
r real system call is _exit
¥ example:
r does some tidying up
r program test-exit.c:
main()
{
exit(3);
}
r run it:
$ cc -o test-exit test-exit.c
$ test-exit
$ echo $?
3
$
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/5
system calls and library calls
¥ system calls
r executed by the operating system
r perform simple single operations
¥ library calls
r executed in the user program
r may perform several tasks
r may call system calls
¥ distinction blurs
r often a thin layer
r compatability with older UNIX calls (e.g. pipe)
¥ kinds of library:
r UNIX functions Ð layers and O/S utilities
r stdio & ANSI C libraries
Ð platform independent functions
r other libraries
Ð for specialist purposes (e.g. NAG)
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/6
system call conventions
¥ library functions often return pointers
FILE * fp = fopen("harry","r");
⇒ NULL return for failure
¥ system calls usually return an integer
int res = sys_call(some_args)
¥ return value
r res >= 0 Ð OK
r res < 0 Ð failure
¥ opposite way round!
⇒ cannot use as Boolean:
if ( sys_call(some_args) ) { ... $ wrong
¥ see the global variable errno for more info
¥ many system calls take simple arguments
¥ but some take special structures
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/7
how they work
x program gets to the system call in the userÕs code
int res = sys_call(some_parameters)
y puts the parameters on the stack
z performs a system ÔtrapÕ Ð hardware dependent
C C now in system mode C C
{ operating system code may copy large data
structures into system memory
| starts operation
if the operation cannot be completed immediately
UNIX may run other processes at this point
} operation complete!
~ if necessary copies result data structures back to
user programÕs memory
 C C return to user mode C C
€ user program puts return code into res
 program recommences
¥ UNIX tries to make it as cheap and fast as possible
¥ but system calls are still ÔexpensiveÕ
(compared to ordinary functions)
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/8
finding out
¥ donÕt expect to remember everything
. . . I donÕt!
¥ even if you did versions differ
¥ places to look:
r manuals
Ð paper or using man command
Ð may need to give man the section:
e.g. man 2 stat
r apropos
Ð especially to find the right man page
e.g. apropos directory
r look at the source!
Ð read the include file
Ð find the right include file:
fgrep dirent /usr/include/*.h
fgrep dirent /usr/include/sys/*.h
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/9
UNIX manuals
¥ divided into sections
1 Ð shell commands
e.g. mv, ls, cat
2 Ð system calls
e.g. _exit, read, write
3 Ð library calls (including stdio)
e.g. exit, printf
4 Ð device and network specific info
e.g. mv, ls, cat
5 Ð file formats
e.g. passwd, termcap
6 Ð games and demos
e.g. fortune, worms
7 Ð miscellaneous
e.g. troff macros, ascii character map
8 Ð admin functions
e.g. fsck, network daemons
¥ UNIX manual reading . . .
. . . a bit of an art
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/10
UNIXSystems
Programming I
Session 2
file I/O and filters
¥ standard input and output
¥ filters
¥ using read and write
¥ opening and closing files
¥ low-level I/O vs. stdio
¥ mixing them
 using it
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/11
input and output
each running program has numbered input/outputs:
0 Ð standard input
¥ often used as input if no file is given
¥ default input from the user terminal
1 Ð standard output
¥ simple program's output goes here
¥ default output to the user terminal
2 Ð standard error
¥ error messages from user
¥ default output to the user terminal
these numbers are called file descriptors
¥ used by system calls to refer to files
0 1
2
input output
errors
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/12
redirecting from the shell
default input/output is user's terminal
redirection to or from files:
r command fred
Ð standard input from file 'fred'
0 1
2
output
errors
'fred'
r command harry
Ð standard output goes to file 'harry'
0 1
2
input
errors
'harry'
Ð file is created if it doesn't exist
N.B. C shell prevents overwriting
r command harry
Ð similar, but appends to end of 'harry'
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/13
redirection of standard error
r command 2errlog
Ð standard error goes to file 'errlog'
0 1
2
input output
'errlog'
r command 2errlog
Ð standard error appends to end of 'errlog'
r command 21
Ð standard error goes to current
destination of standard output
0 1
2
input output
errors
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/14
filters
¥ some commands only work on named
files:
e.g. copying Ð cp from-file to-file
¥ many take standard input as default
cat, head, tail, cut, paste, etc.
¥ these are called filters
Ð very useful as part of pipes
¥ also very easy to program!
donÕt have to worry about
r command line arguments
r opening or closing files
¥ just read-process-write
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/15
read  write
ret = read(fd,buff,len)
int fd Ð a file descriptor (int), open for reading
char *buff Ð buffer in which to put chars
int len Ð maximum number of bytes to read
int ret Ð returns actual number read
¥ ret is 0 at end of file, negative for error
¥ buff is not NULL terminated
leave room if you need to add Ô0Õ!
ret = write(fd,buff,len)
int fd Ð a file descriptor (int), open for writing
char *buff Ð buffer from which to get chars
int len Ð number of bytes to write
int ret Ð returns actual number written
¥ ret is negative for error, 0 means Òend of fileÓ
ret may be less than len e.g. if OS buffers full
* should really check and repeat until all gone *
¥ buff need not be NULL terminated
if buff is a C string, use strlen to get its length
N.B. Both may return negative after interrupt (signal)
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/16
example – file translation
¥ a Macintosh → UNIX text file conversion program
main() {
char buf[256];
for(;;) {
int i
int n = read(0,buf,256); Œ
if ( n = 0 ) exit(-n); y
for ( i=0; in; i++ )
if ( buff[i] == ‘r’ ) z
buff[i] = ‘n’;
write(1,buf,n); {
}
exit(0);
}
x read from file descriptor 0 Ð standard input
buffer size is 256 bytes
number of bytes read goes into n
y end of file (0) or error (n0) both exit
the -n means that end of file gives a zero exit code
z Macintosh uses carriage return 'r' to end lines
UNIX uses newline 'n'
{ writing to 1 Ð standard output
remember only write n bytes not 256!
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/17
opening and closing files
#include fcntl.h
int fd = open(name,flags)
char *name Ð name of the file to open
int flags Ð read/write/append etc.
int fd Ð returns a file descriptor
¥ in simple use flags is one of:
O_RDONLY Ð read only (0)
O_WRONLY Ð write only (1)
O_RDWR Ð read and write (2)
but can ÔorÕ in other options
¥ negative result on failure
r file doesnÕt exist
r do not have permissions
¥ closing files is simpler!
int res = close(fd)
int fd Ð an open file descriptor
int ret Ð returns: 0 OK
-1 failed
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/18
low-level I/O vs. stdio
¥ why use low-level I/O?
r less layers ≈ more efficient
r more control Ð e.g. random access
r sometimes have to Ð e.g. networks
¥ can you mix low-level I/O and stdio?
yes
$ with care!
¥ different files/devices
no problem
¥ same file
$ stdio is buffered
printf(hello );
write(1,there ,6);
printf(worldn);
¯ output:
there hello world
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/19
    Hands on    
 write a simple cypher filter: cypher.c
 the filter should copy standard input to standard
output adding 1 to each byte:
a→b, b→c, c→d, d→e, etc.
 it will be similar to the Mac→UNIX translator
except that the loop should add 1 rather than
replace carriage returns with line feeds
 to make a better cypher, you could add a different
number or have a 256 byte array to act as the cypher
 compile either with ÔccÕ Ð the old KR C compiler:
cc -o cypher cypher.c
 or with ÔaccÕ Ð the ANSI C compiler:
cc -o cypher cypher.c
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/20
UNIXSystems
Programming I
Session 3
makefiles and
arguments
¥ make
¥ argv and argc
¥ environment variables
 using it
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/21
make
ÔmakeÕ is a UNIX command which:
¥ automates program construction and linking
¥ tracks dependencies
¥ keeps things up-to-date after changes
to use it:
r construct a file with rules in it
you can call it anything, but ÔmakefileÕ is the default
r run ÔmakeÕ itself
make target
– (uses the default makefile)
make -f myfile target
– (uses the rule file myfile)
either rebuilds the program ÔtargetÕ if necessary
¥ each makefile consists of:
r definitions
r rules
¥ rules say how one thing depends on another
they are either:
r specific Ð e.g. to make mail-client do this ...
r generic Ð e.g. to make any Ô.oÕ from its Ô.cÕ ...
make is also available in many other programming environments
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/22
makefile format
Definitions
¥ general form:
variable = value
¥ example:
SDIR = tcp
MYLIBS = $(SDIR)/lib
N.B. one variable used in another's definition
¥ make variables are referred to later using $
e.g.$(SDIR), $(MYLIBS)
¥ expanded like #defines or shell variables
(some versions of make will expand shell variables also)
Rules (just specific rules)
¥ general form:
target : dependent1 dependent2 ...
command-line
↑ N.B. this must be a tab
¥ example:
myprog: myprog.o another.o
cc -o myprog myprog.o another.o $(MYLIBS)
this says:
to make myprog you need myprog.oandanother.o
if either of them is newer than myprog rebuild it using the
then rebuild it using the command: Òcc -o myprog ...Ó
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/23
argc  argv
int main( int argc, char **argv ) ...
or: int main( int argc, char *argv[ ] ) ...
¥ one of the ways to get information into a C program
¥ in UNIX you type:
myprog a b c d
the program gets:
argc = 4 Ð length of argv
argv[0] = myprog Ð program name
argv[1] = a
argv[2] = b c Ð single second argument
argv[3] = d
argv[4] = NULL Ð terminator
N.B. r DOS is identical (except argv[0] is NULL early versions)
r argc is one less than the number of arguments!
¥ other ways to get information in (UNIX  DOS):
r configuration file (known name)
r standard input
r environment variables using getenv()
or (UNIX only) third arg to main:
main(int argc, char **argv, char **envp)
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/24
environment variables
¥ set of name=value mappings
¥ most created during start-up (.profile, .login etc.)
setting a variable from the shell:
myvar=hello
var2= a value with spaces needs to be quoted
export myvar
¥ no spaces before or after '=' sign
¥ variables need to be exported to be seen
by other programs run from the shell
¥ in C shell: set name=val and no export
listing all variables from the shell:
$ set
HOME=/home/staff2/alan
myvar=hello
PATH=/local/bin:/bin:/local/X/bin
USER=alan
. . .
$
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/25
environment variables – 2
¥ accessing from a program Ð 3 methods
x extra argument to main
main(int argc,char **argv,char **envp)
y global variable
extern char **environ
z system function
char *value = getenv(name);
¥ both x and y give you a structure similar to argv
r a null terminated array of strings
r but environment strings are of the form
name=value
¥ the getenv function z rather different
r fetches the value associated with name
r returns NULL if name not defined
¥ also a putenv function
r only available to this process and its children
r not visible to the shell that invoked it
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/26
    Hands on    
 write a program to produce a list of arguments as in
the 'argc  argv' slide
 the core of your program will look something like:
for(i=0; iargc; i++)
printf(argv[%d] = %sn,argv[i]);
 if you use ÔccÕ then the ÔmainÕ program begins:
main(argc,argv)
int argc;
char **argv;
the slide shows the ANSI C declaration
 do a similar program for environment variables
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/27
UNIXSystems
Programming I
Session 4
file manipulation
¥ creating new files
¥ ÔdeletingÕ files
¥ linking to existing files
¥ symbolic links
¥ renaming files
¥ creating/removing directories
 using it
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/28
creating files
int fd = creat(path,mode)
char *path Ð the name/path of the (new) file
int mode Ð permissions for the new file
int fd Ð returns a file descriptor
¥ file is created if it doesnÕt exist
¥ if it already exists, acts like an open for writing
¥ negative return on failure
¥ mode sets the initial permissions, e.g.
mode = S_RWXUSR | S_IRGRP | S_IXGRP | S_IXOTH
Ð read/write/execute for user (S_RWXUSR)
Ð read/execute for group (S_IRGRP | S_IXGRP)
Ð execute only for others (S_IXOTH)
¥ when created, file descriptor is open for writing
f even if permissions do not include write access
¥ alternative Ð use open with special flags:
int fd = open( path, O_WRONLY|O_CREAT|O_TRUNC, mode )
¥ O_CREAT flag says Òcreate if it doesnÕt existÓ
¥ note extra mode parameter
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/29
deleting files
¥ UNIX rm command ÔdeletesÕ files
¥ it uses the unlink system call
int res = unlink(path)
char *path Ð the name/path of the file to remove
int mode Ð permissions for the new file
int res Ð returns an integer 0 Ð OK
-1 Ð fail
¥ doesnÕt necessarily delete file!
¥ but neither does rm
¥ UNIX filenames are pointers to the file
¥ there may be more than one pointer
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/30
hard links
¥ linking to an existing file:
r shell Ð ln tom fred
r system call Ð link(tom,fred)
¥ file tom must already exist
¥ fred points to the same file as tom
tomfred
¥ unlink simply removes a pointer
¥ file destroyed only when last link goes
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/31
symbolic links
¥ ÔhardÕ links are limited:
r cannot link to a different disk
r only one link to a directory
(actually not quite true as there are all the Ò..Ó links)
¥ symbolic links are more flexible
r shell Ð ln -s tom fred
r system call Ð symlink(tom,fred)
¥ tom need not exist
¥ fred points to the name ÔtomÕ Ð an alias
tomfred
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/32
links and updates
cp fred tom ln fred tom ln -s fred tom
fred tom tomfred tomfred
¥ update file tom
fred tom tomfred tomfred
¥ delete file tom Ð unlink(tom)
fred tom tomfred tomfred
¥ what is in fred?
fred fred ?fred
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/33
renaming files
int res = rename(path1,path2)
char *path Ð the name/path of the (new) file
int fd Ð returns a file descriptor
¥ system call used by UNIX mv command
¥ only possible within a file system
x path2 is unlinked
y path2 is linked to the file pointed to by path1
z path1 is unlinked
¥ result: path2 points to the file path1 used to point to
e.g. rename(fred,tom)
fred tom fred tom
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/34
directories
¥ special system calls
to create and remove directories
int res = mkdir(path,mode)
char *path Ð the path of the new directory
int mode Ð permissions for the new directory
int res Ð returns an integer 0 Ð OK
-1 Ð fail
¥ mkdir rather like creat
int res = rmdir(path)
char *path Ð the path of the directory to remove
int res Ð returns an integer 0 Ð OK
-1 Ð fail
¥ unlike unlink does delete directory!
¥ but only when empty
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/35
    Hands on    
 rm has various options
 so it is hard to delete files with strange names
such as Ô-bÕ Ð I know I got one once!
 write a program raw-rm.c which has one command
line argument, a file to delete, and performs an
unlink system call on it
 modify raw-rm so that it can take a list of files:
raw-rm tom dick harry
 write a version of mv that doesnÕt use the rename
system call, but only link and unlink
 N.B. if you get the order wrong youÕll loose the file!
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/36
UNIXSystems
Programming I
Session 5
terminal I/O
¥ terminals are just files?
¥ tty drivers
¥ stty and gtty
¥ handling input
¥ the termcap database
¥ toolkits
 using it
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/37
terminals are easy?
¥ terminal is default input/output
¥ read and write just like any file
r use read/write system calls
r or stdio
¥ interactive programs Ð a doddle
printf(what is your name? );
gets(buff);
printf(hello %s how are you todayn,buff);
get line editing for free
$ paper-roll model of interaction
r only see user input in whole lines
¥ terminals not quite like other files:
r write anywhere on screen
r cursor movement
r special effects (flashing, colours etc.)
r non-standard keys: ctrl, alt, F3 etc.
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/38
tty drivers
¥ never connected directly to terminal
¥ tty driver sits between
r does line editing
r handles break keys and flow control
(ctrl-C, ctrl-, ctrl-S/ctrl-Q)
r translates delete/end-of-line chars
¥ not always wanted!
your
program
tty driver
UNIX kernal
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/39
stty command
¥ control the tty driver from the shell
$ stty everything
$ stty -echo
$  type something Ð no echo
$ reset
¥ stty differs between UNIXs!
¥ can control
r echoing
r parity, stop bits etc. for modems
r carriage return / newline mapping
r delete key mapping (delete/backspace)
r break key activity
r line editing
. . . and more
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/40
gtty  stty functions
¥ you can do the same from a program
#include sgtty.h
int echo_off(tty_fd)
int tty_fd;
{
struct sgttyb buf;
gtty(tty_fd,buf);
buf.sg_flags = ~ECHO;
return stty(tty_fd,buf);
}
¥ sg_flags Ð a bitmap of option flags
¥ the sgttyb structure has other fields
r line speeds ( sg_ispeed, sg_ospeed)
r erase and kill chars ( sg_erase, sg_kill)
(word and line delete)
¥ gtty and stty depreciated now
r more options available through ioctl
r but they are the ÔtraditionalÕ UNIX calls
r and simpler!
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/41
raw, cbreak and cooked
¥ normal tty processing
r echoing of all input
r some output translation
r line editing
r break characters
called ÔcookedÕ mode
¥ visual programs do not want this
r use stty or ioctl to control
¥ raw mode
buf.sg_flags |= RAW;
r suppress all input and output processing
r echoing still occurs Ð use ECHO bit
¥ cbreak (half-cooked) mode
buf.sg_flags |= CBREAK;
r as for raw
r but break key (ctrl-C) enabled
Ì remember to save and reset the mode!
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/42
handling input
¥ with raw  cbreak
r donÕt have to wait for a line end
r get characters as they are typed
r including delete key
¥ key → input mapping?
r simple for ascii keys: A key → ÔaÕ etc.
r others → single char: backspace → 0x8
r some → lots i key → ESC [A
¥ prefixes
r one key may be a prefix of another!
e.g. function key F3 → ESC[19~
escape key → ESC
r you read ESC
? how do you know which key
¥ solutions
x wait for next character
$ could wait a long time!
y assume that the whole code is read at once
$ not always true
z as x but with timeout
$ best solution
$ introduces delays
$ may still fail (swopped out)
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/43
termcap
¥ different kinds of terminals
r different screen sizes (80x25?)
r different capabilities (flashing, underline, ...)
r different keyboards
r different screen control characters
¥ how do you know what to do?
$ write terminal specific code
use termcap
x environment variable TERM
gives terminal type e.g. vt100, vt52 etc.
y /etc/termcap database
gives capabilities and codes for each type
d0|vt100|vt100-am|vt100am|dec vt100:
:do=^J:co#80:li#24:cl=50E[;HE[2J:sf=5ED:
:le=^H:bs:am:cm=5E[%i%d;%dH:nd=2E[C:up=2E[A:
 7 more lines! 
r each item gives a code/capability
e.g. do=^J Ð send ctrl-J to move cursor down
co#80 Ð 80 columns
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/44
termcap library
¥ read /etc/termcap directly?
¥ termcap library has functions to help
cc -o my-vis my-vis.c -ltermcap
r tgetent(val,tname)
Ð get the info for terminal tname
r tgetnum(id)
Ð return the number for capability id
r tgetflag(id)
Ð test for capability id
r tgetstr(id)
Ð return the string value for id
r tgoto(code,col,line)
Ð generate a cursor addressing string
r tputs(str,lines_affected,output_f)
Ð outputs with appropriate padding
¥ not exactly a high-level interface
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/45
curses and toolkits
¥ various high-level toolkits available
e.g. curses, C-change
¥ curses is the UNIX old-timer!
cc -o my-cur my-cur.c -lcurses -ltermcap
¥ many functions including:
r initscr() endwin()
Ð start and finish use
r move(line,col)
Ð cursor positioning
r printw(fmt, ...)
Ð formatted output
r mvprintw(line,col,fmt, ...)
Ð both together!
r mvgetch(l,c), mvgetstr(l,c,buf)
Ð read user input
r mvinch()
Ð read screen
r clear(), refresh()
Ð clear and refresh screen
r cbreak(), nocbreak(), echo(), raw(),
Ð setting terminal mode
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/46
    Hands on    
 use stty at the shell to set echo, cbreak and raw
$ cat
 type a few lines to see what it normally does 
^D
$ stty cbreak
$ cat
 type a bit 
^D
$ stty raw
$ echo hello
 use cat to see what codes your terminal produces
$ cat
 type lots of keys and things 
^D
$
 try entering and running the following:
#include curses.h
main()
{
initscr();
clear();
mvprintw(10,30,hello world!);
move(20,5);
refresh();
endwin();
}
 what happens if you leave out the refresh()call
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/47
UNIXSystems
Programming I
Session 6
signals and time
¥ what are signals
¥ the signal system call
¥ problems of concurrency
¥ finding the time
¥ going to sleep
 using it
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/48
signals
¥ interacting with the world
r file/tty input Ð what
r signals Ð when
¥ signals happen due to:
r errors
SIGFPE Ð floating point error
SIGSEGV Ð segment violation
(usually bad pointer!)
r interruptions
SIGKILL Ð forces process to die
SIGINT Ð break key (ctrl-C)
r things happen
SIGALRM Ð timer expires
SIGCHLD Ð child process has died
r I/O event
SIGURG Ð urgent data from network
SIGPIPE Ð broken pipe
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/49
catching signals
¥ default action for signals
r some abort the process
r some ignored
¥ you can do what you like
r so long as you catch the signal
r and itÕs not SIGKILL(signal 9)
x write the code that you want run
int my_handler()
{
my_flag = 1n”;
}
y use the signal system call to tell UNIX about it
signal(SIGQUIT,my_handler);
z when the signal occurs UNIX calls my_handler
{ when you no longer require a signal to be caught
signal(SIGQUIT,SIG_IGN);
signal(SIGFPE,SIG_DFL);
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/50
care with signals
¥ signal handlers can run at any time
int i = 0;
int my_handler()
{
i = i + 1;
}
main()
{
signal(SIGINT,my_handler);
for(;;)
if ( i  0 ) {
do_something();
i = i - 1;
}
}
¥ intention:
execute do_something once per interrupt
¥ what actually happens:
x interrupt processed (i=1)
y do_something executes
z main calculates i-1 gets result 0
{ before it stores the result . . .
. . . another interrupt (i=2)
| main stores result (i=0)
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/51
working with time
¥ processes need to tell the time
r absolute time: 15:17 on Thursday 21st March
r elapsed time: that took 3.7 seconds
¥ and time their actions
r delays: wait for 5 seconds
r alarms: at 11.15pm do the backup
¥ delays easy
r sleep(t) system call
r waits for t seconds
r at least!
sleep(5); /* waits for at least 5 seconds */
¥ cannot guarantee time
r other processes may be running
r not a real-time operating system
¥ alarms covered in UNIX Systems Programming II
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/52
finding the time
¥ UNIX time started on 1st January 1970!
¥ time system call returns seconds 1/1/1970
#include sys/types.h
#include sys/time.h
time_t t = time(NULL);
¥ ftime gives you milliseconds and timezone too
#include sys/timeb.h
struct timeb tmb;
int res = ftime(tmb);
¥ the process does not run all the time
clock gives cpu time used in µsecs
long cpu_t = clock();
N.B. times gives you more information about cpu usage
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/53
telling the time
¥ users donÕt measure time in seconds since 1/1/1970!
¥ collection of functions to do conversions
between four time formats
x seconds since 1/1/1970
y struct timeb (from ftime)
z struct tm (gives year, day, hour etc.)
{ ascii representation as C string:
Sun Sep 16 01:03:52 1973n
x → z localtime, gmtime
z → { asctime
x → { ctime
z → x timelocal, timegm
r also dysize(yr) Ð number of days in year yr
¥ local variants give local time
gm variants give Greenwich Mean Time
¥ see man 3 ctime for more details
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/54
    Hands on    
 write a program to see how ÔlazyÕ sleep is!
 it should:
x get the time using both clockandtime
y print both
z do a sleep(5)
{ get the times again
| and print them
 run it several times and record the results
 printing at y adds a delay,
modify the above plan to make it right
and also get it to print the time elapsed as
measured by clockandtime
 run this version and compare results with the first
 try the program in the Òcare with signalsÓ slide
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/55
UNIXSystems
Programming I
Session 7
mixing C and scripts
¥ shell scripts
¥ what are they good for?
¥ information shell → C
¥ results C → shell
 example
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/56
shell
¥ the shell is a programming language
r data:
environment variables (character strings)
whole files
r control flow:
similar + special features
r procedures:
shell scripts
¥ shell and C:
r shell:
good at manipulating files and programs
$ slow for intensive calculation
r C:
fast and flexible
$ longer development cycle
¥ use them together
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/57
shell scripts
¥ shell scripts are files:
x starting with:
#!/bin/sh
y containing shell commands
z made executable by
chmod a+x
¥ executed using a copy of the shell
$ cat my-first-script
#!/bin/sh
echo hello world
$ chmod a+x my-first-script
$ my-first-script
hello world
$
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/58
it’s good to talk
¥ shell and C need to communicate
¥ shell → C
r standard input:
large amounts of data
r command line arguments:
file names, options
r environment variables:
long-term preferences  settings
¥ C → shell
r standard output:
large amounts of data
r standard error:
$ normally only to the user
r exit code:
success/failure or single number
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/59
shell → C
¥ standard input
Ð not just files!
r single line Ð use echoand pipe
echo hello | myprog
r lots of lines Ð use HERE file
my-prog HERE
this is two lines
 of text
 HERE
¥ command line arguments
r shell pattern matching is great
r let it check and pass good args in
¥ environment variables
r inwards only!
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/60
C → shell
¥ standard output
r redirect to file
my-prog some-args  fred.out
r pipe it
my-prog some-args | more-progs
r or use backquotes!
myvar=`my-prog some-args`
¥ exit code
r remember: 0 = success
r use if, while etc.
if my-prog some-args
then
echo OK
else
echo failed
fi
r or use $?
my-prog some-args
echo returned $?
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/61
    example    
 the following numc.c is a filter for numbering lines
#include stdio.h
char buff[256];
main()
{
int lineno;
for ( lineno=1; gets(buff); lineno++ )
printf(%4d: %sn,lineno,buff);
}
 we would like to give it arguments
$ numc fred
1: fred’s first line
2: the second line of fred
$ too much work!
use a shell script
 weÕll call it num
#!/bin/sh
case $# in
0) numc; exit 0;; # filter mode
esac
for i # loops through all arguments
do
echo; echo ---- $i ----
numc $i
done
UNIXSystems
ProgrammingI Short Course Notes Alan Dix © 1996 I/iii
random access
¥ normally read/write are serial
r move forward byte by byte through the file
¥ lseek allows random access
off_t pos = lseek(fd,offset,flag)
int fd Ð an open file descriptor
off_t offset Ð number of bytes to seek
(negative means back)
int flag Ð where to seek from:
L_SET Ð beginning of file
L_INCR Ð current position
L_XTND Ð end of file
off_t pos Ð the old position in the file
(N.B. off_t is actually a long int!)
¥ moves the I/O position forward or back by offset
¥ finding where you are without moving:
r move zero (0L) from current position (L_INCR)
r tell function Ð used to be a system call!

More Related Content

What's hot

101 1.3 runlevels , shutdown, and reboot
101 1.3 runlevels , shutdown, and reboot101 1.3 runlevels , shutdown, and reboot
101 1.3 runlevels , shutdown, and rebootAcácio Oliveira
 
Unit 10 investigating and managing
Unit 10 investigating and managingUnit 10 investigating and managing
Unit 10 investigating and managingroot_fibo
 
AllBits presentation - Lower Level SW Security
AllBits presentation - Lower Level SW SecurityAllBits presentation - Lower Level SW Security
AllBits presentation - Lower Level SW Security
AllBits BVBA (freelancer)
 
The Ring programming language version 1.3 book - Part 60 of 88
The Ring programming language version 1.3 book - Part 60 of 88The Ring programming language version 1.3 book - Part 60 of 88
The Ring programming language version 1.3 book - Part 60 of 88
Mahmoud Samir Fayed
 
Unix(introduction)
Unix(introduction)Unix(introduction)
Unix(introduction)meashi
 
Desktop Forensics: Windows
Desktop Forensics: WindowsDesktop Forensics: Windows
Desktop Forensics: Windows
Gol D Roger
 
Dc 12 Chiueh
Dc 12 ChiuehDc 12 Chiueh
Dc 12 Chiuehwollard
 
101 3.2 process text streams using filters
101 3.2 process text streams using filters101 3.2 process text streams using filters
101 3.2 process text streams using filters
Acácio Oliveira
 
101 3.2 process text streams using filters
101 3.2 process text streams using filters101 3.2 process text streams using filters
101 3.2 process text streams using filters
Acácio Oliveira
 
Nguyễn Vũ Hưng: Basic Linux Power Tools
Nguyễn Vũ Hưng: Basic Linux Power Tools Nguyễn Vũ Hưng: Basic Linux Power Tools
Nguyễn Vũ Hưng: Basic Linux Power Tools
Vu Hung Nguyen
 
Linux Security Quick Reference Guide
Linux Security Quick Reference GuideLinux Security Quick Reference Guide
Linux Security Quick Reference Guidewensheng wei
 
Linux Introduction (Commands)
Linux Introduction (Commands)Linux Introduction (Commands)
Linux Introduction (Commands)
anandvaidya
 
System calls
System callsSystem calls
System calls
AfshanKhan51
 
Unix_commands_theory
Unix_commands_theoryUnix_commands_theory
Unix_commands_theoryNiti Patel
 
Part 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in Linux
Tushar B Kute
 
Exploits
ExploitsExploits
ExploitsKen Sai
 
1.2 boot the system v2
1.2 boot the system v21.2 boot the system v2
1.2 boot the system v2
Acácio Oliveira
 
운영체제론 Ch20
운영체제론 Ch20운영체제론 Ch20
운영체제론 Ch20
Jongmyoung Kim
 

What's hot (20)

101 1.3 runlevels , shutdown, and reboot
101 1.3 runlevels , shutdown, and reboot101 1.3 runlevels , shutdown, and reboot
101 1.3 runlevels , shutdown, and reboot
 
Unit 10 investigating and managing
Unit 10 investigating and managingUnit 10 investigating and managing
Unit 10 investigating and managing
 
AllBits presentation - Lower Level SW Security
AllBits presentation - Lower Level SW SecurityAllBits presentation - Lower Level SW Security
AllBits presentation - Lower Level SW Security
 
The Ring programming language version 1.3 book - Part 60 of 88
The Ring programming language version 1.3 book - Part 60 of 88The Ring programming language version 1.3 book - Part 60 of 88
The Ring programming language version 1.3 book - Part 60 of 88
 
Unix(introduction)
Unix(introduction)Unix(introduction)
Unix(introduction)
 
Desktop Forensics: Windows
Desktop Forensics: WindowsDesktop Forensics: Windows
Desktop Forensics: Windows
 
Dc 12 Chiueh
Dc 12 ChiuehDc 12 Chiueh
Dc 12 Chiueh
 
101 3.2 process text streams using filters
101 3.2 process text streams using filters101 3.2 process text streams using filters
101 3.2 process text streams using filters
 
101 3.2 process text streams using filters
101 3.2 process text streams using filters101 3.2 process text streams using filters
101 3.2 process text streams using filters
 
Nguyễn Vũ Hưng: Basic Linux Power Tools
Nguyễn Vũ Hưng: Basic Linux Power Tools Nguyễn Vũ Hưng: Basic Linux Power Tools
Nguyễn Vũ Hưng: Basic Linux Power Tools
 
Linux Security Quick Reference Guide
Linux Security Quick Reference GuideLinux Security Quick Reference Guide
Linux Security Quick Reference Guide
 
Linux Introduction (Commands)
Linux Introduction (Commands)Linux Introduction (Commands)
Linux Introduction (Commands)
 
System calls
System callsSystem calls
System calls
 
Unix_commands_theory
Unix_commands_theoryUnix_commands_theory
Unix_commands_theory
 
Part 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in Linux
 
Exploits
ExploitsExploits
Exploits
 
1.2 boot the system v2
1.2 boot the system v21.2 boot the system v2
1.2 boot the system v2
 
Rar
RarRar
Rar
 
lec4.docx
lec4.docxlec4.docx
lec4.docx
 
운영체제론 Ch20
운영체제론 Ch20운영체제론 Ch20
운영체제론 Ch20
 

Viewers also liked

basic shell_programs
 basic shell_programs basic shell_programs
basic shell_programsmadhugvskr
 
Shell Scripts
Shell ScriptsShell Scripts
Shell ScriptsDr.Ravi
 
Unix Shell Scripting Tutorial | Unix Shell Scripting Online Training
Unix Shell Scripting Tutorial | Unix Shell Scripting Online TrainingUnix Shell Scripting Tutorial | Unix Shell Scripting Online Training
Unix Shell Scripting Tutorial | Unix Shell Scripting Online Training
Vyshnavi Reddy
 
Unix shell program training
Unix shell program trainingUnix shell program training
Unix shell program training
Aditya Sharat
 
Unix Shell Script
Unix Shell ScriptUnix Shell Script
Unix Shell Scriptstudent
 
Adbms lab manual
Adbms lab manualAdbms lab manual
Adbms lab manual
RAKESH KUMAR
 
M.TECH 1ST SEM COMPUTER SCIENCE AOS LAB PRGMS 2014
M.TECH 1ST SEM COMPUTER SCIENCE AOS LAB PRGMS 2014M.TECH 1ST SEM COMPUTER SCIENCE AOS LAB PRGMS 2014
M.TECH 1ST SEM COMPUTER SCIENCE AOS LAB PRGMS 2014
Supriya Radhakrishna
 
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMSM.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
Supriya Radhakrishna
 

Viewers also liked (10)

basic shell_programs
 basic shell_programs basic shell_programs
basic shell_programs
 
Unix1
Unix1Unix1
Unix1
 
Shell Scripts
Shell ScriptsShell Scripts
Shell Scripts
 
Chap06
Chap06Chap06
Chap06
 
Unix Shell Scripting Tutorial | Unix Shell Scripting Online Training
Unix Shell Scripting Tutorial | Unix Shell Scripting Online TrainingUnix Shell Scripting Tutorial | Unix Shell Scripting Online Training
Unix Shell Scripting Tutorial | Unix Shell Scripting Online Training
 
Unix shell program training
Unix shell program trainingUnix shell program training
Unix shell program training
 
Unix Shell Script
Unix Shell ScriptUnix Shell Script
Unix Shell Script
 
Adbms lab manual
Adbms lab manualAdbms lab manual
Adbms lab manual
 
M.TECH 1ST SEM COMPUTER SCIENCE AOS LAB PRGMS 2014
M.TECH 1ST SEM COMPUTER SCIENCE AOS LAB PRGMS 2014M.TECH 1ST SEM COMPUTER SCIENCE AOS LAB PRGMS 2014
M.TECH 1ST SEM COMPUTER SCIENCE AOS LAB PRGMS 2014
 
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMSM.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
 

Similar to Prog i

lect01.ppt
lect01.pptlect01.ppt
lect01.ppt
DrSamsonChepuri1
 
Linux Commands
Linux CommandsLinux Commands
Linux Commands
Ramasubbu .P
 
Linuxppt
LinuxpptLinuxppt
LinuxpptReka
 
Unix And C
Unix And CUnix And C
Unix And CDr.Ravi
 
Summarized of UNIX Time Sharing System
Summarized of UNIX Time Sharing SystemSummarized of UNIX Time Sharing System
Summarized of UNIX Time Sharing System
Shuya Osaki
 
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using PipesLinux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
RashidFaridChishti
 
Write a C program called pross-c to implement the UNIX-Linux equivalen.docx
Write a C program called pross-c to implement the UNIX-Linux equivalen.docxWrite a C program called pross-c to implement the UNIX-Linux equivalen.docx
Write a C program called pross-c to implement the UNIX-Linux equivalen.docx
SUKHI5
 
Unix
UnixUnix
Unix Administration 2
Unix Administration 2Unix Administration 2
Unix Administration 2
Information Technology
 
Operating System Laboratory presentation .ppt
Operating System Laboratory presentation .pptOperating System Laboratory presentation .ppt
Operating System Laboratory presentation .ppt
PDhivyabharathi2
 
Lamp ppt
Lamp pptLamp ppt
Lamp pptReka
 
Basics of unix
Basics of unixBasics of unix
Basics of unix
Arnold Derrick Kinney
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manualSami Said
 
Bioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionBioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introduction
Prof. Wim Van Criekinge
 

Similar to Prog i (20)

Unix
UnixUnix
Unix
 
Nithi
NithiNithi
Nithi
 
lect01.ppt
lect01.pptlect01.ppt
lect01.ppt
 
Prog ii
Prog iiProg ii
Prog ii
 
Linuxppt
LinuxpptLinuxppt
Linuxppt
 
Linux Commands
Linux CommandsLinux Commands
Linux Commands
 
Linuxppt
LinuxpptLinuxppt
Linuxppt
 
Unix And C
Unix And CUnix And C
Unix And C
 
Linuxs1
Linuxs1Linuxs1
Linuxs1
 
Linuxppt
LinuxpptLinuxppt
Linuxppt
 
Summarized of UNIX Time Sharing System
Summarized of UNIX Time Sharing SystemSummarized of UNIX Time Sharing System
Summarized of UNIX Time Sharing System
 
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using PipesLinux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
 
Write a C program called pross-c to implement the UNIX-Linux equivalen.docx
Write a C program called pross-c to implement the UNIX-Linux equivalen.docxWrite a C program called pross-c to implement the UNIX-Linux equivalen.docx
Write a C program called pross-c to implement the UNIX-Linux equivalen.docx
 
Unix
UnixUnix
Unix
 
Unix Administration 2
Unix Administration 2Unix Administration 2
Unix Administration 2
 
Operating System Laboratory presentation .ppt
Operating System Laboratory presentation .pptOperating System Laboratory presentation .ppt
Operating System Laboratory presentation .ppt
 
Lamp ppt
Lamp pptLamp ppt
Lamp ppt
 
Basics of unix
Basics of unixBasics of unix
Basics of unix
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manual
 
Bioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionBioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introduction
 

Recently uploaded

Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 

Recently uploaded (20)

Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 

Prog i

  • 1. UNIX Systems Programming I Short Course Notes Alan Dix © 1996 http://www.hcibook.com/alan/ UNIXSystems Programming I UNIXSystems Programming I UNIXSystems Programming I UNIXSystems Programming I UNIXSystems Programming I
  • 2. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/i UNIXSystems Programming I Course Outline Alan Dix http://www.hcibook.com/alan/ Session 1 UNIX basics the UNIX API, system calls and manuals Session 2 file I/O and filters standard input and output, read, write and open Session 3 makefiles and arguments make, argc & argv and environment variables Session 4 file manipulation creating and deleting files and directories, links and symbolic links Session 5 terminal I/O similarities to file I/O, ttyÊdrivers, stty & gtty, termcap and curses Session 6 signals and time catching signals and problems that arise, delays and finding the time Session 7 mixing C and scripts shell scripts, getting information between C and shell, putting them together
  • 3. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/ii UNIXSystems Programming I Reading ¥ The Unix V Environment, Stephen R. Bourne, Wiley, 1987, ISBN 0 201 18484 2 The author of the Borne Shell! A 'classic' which deals with system calls, the shell and other aspects of UNIX. ¥ Unix For Programmers and Users, Graham Glass, Prentice-Hall, 1993, ISBN 0 13 061771 7 Slightly more recent book also covering shell and C programming. Ì BEWARE Ð UNIX systems differ in details, check on-line documentation ¥ UNIX manual pages: man creat etc. Most of the system calls and functions are in section 2 and 3 of the manual. The pages are useful once you get used to reading them! ¥ The include files themselves /usr/include/time.h etc. Takes even more getting used to, but the ultimate reference to structures and definitions on your system.
  • 4. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/1 UNIXSystems Programming I Session 1 UNIX basics ¥ the nature of UNIX ¥ the UNIX API ¥ system calls and library calls ¥ system call conventions ¥ how they work ¥ UNIX manuals and other info
  • 5. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/2 UNIX UNIX is an operating system file store programsnetworks etc. UNIX It manages: ¥ files and data ¥ running programs ¥ networks and other resources It is defined by ¥ its behaviour (on files etc.) ¥ its application programmers interface Ð API
  • 6. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/3 UNIX API – the system calls ¥ ultimately everything works through system calls shell file store programsnetworks etc. UNIX API system daemons user applications X
  • 7. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/4 first system call – exit void exit(int status) ¥ program ends! ¥ its exit code is set to status ¥ available to shell: $? Ð Bourne shell $status Ð C shell ¥ actually not a real system call! r does some tidying up r real system call is _exit ¥ example: r does some tidying up r program test-exit.c: main() { exit(3); } r run it: $ cc -o test-exit test-exit.c $ test-exit $ echo $? 3 $
  • 8. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/5 system calls and library calls ¥ system calls r executed by the operating system r perform simple single operations ¥ library calls r executed in the user program r may perform several tasks r may call system calls ¥ distinction blurs r often a thin layer r compatability with older UNIX calls (e.g. pipe) ¥ kinds of library: r UNIX functions Ð layers and O/S utilities r stdio & ANSI C libraries Ð platform independent functions r other libraries Ð for specialist purposes (e.g. NAG)
  • 9. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/6 system call conventions ¥ library functions often return pointers FILE * fp = fopen("harry","r"); ⇒ NULL return for failure ¥ system calls usually return an integer int res = sys_call(some_args) ¥ return value r res >= 0 Ð OK r res < 0 Ð failure ¥ opposite way round! ⇒ cannot use as Boolean: if ( sys_call(some_args) ) { ... $ wrong ¥ see the global variable errno for more info ¥ many system calls take simple arguments ¥ but some take special structures
  • 10. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/7 how they work x program gets to the system call in the userÕs code int res = sys_call(some_parameters) y puts the parameters on the stack z performs a system ÔtrapÕ Ð hardware dependent C C now in system mode C C { operating system code may copy large data structures into system memory | starts operation if the operation cannot be completed immediately UNIX may run other processes at this point } operation complete! ~ if necessary copies result data structures back to user programÕs memory  C C return to user mode C C € user program puts return code into res  program recommences ¥ UNIX tries to make it as cheap and fast as possible ¥ but system calls are still ÔexpensiveÕ (compared to ordinary functions)
  • 11. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/8 finding out ¥ donÕt expect to remember everything . . . I donÕt! ¥ even if you did versions differ ¥ places to look: r manuals Ð paper or using man command Ð may need to give man the section: e.g. man 2 stat r apropos Ð especially to find the right man page e.g. apropos directory r look at the source! Ð read the include file Ð find the right include file: fgrep dirent /usr/include/*.h fgrep dirent /usr/include/sys/*.h
  • 12. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/9 UNIX manuals ¥ divided into sections 1 Ð shell commands e.g. mv, ls, cat 2 Ð system calls e.g. _exit, read, write 3 Ð library calls (including stdio) e.g. exit, printf 4 Ð device and network specific info e.g. mv, ls, cat 5 Ð file formats e.g. passwd, termcap 6 Ð games and demos e.g. fortune, worms 7 Ð miscellaneous e.g. troff macros, ascii character map 8 Ð admin functions e.g. fsck, network daemons ¥ UNIX manual reading . . . . . . a bit of an art
  • 13. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/10 UNIXSystems Programming I Session 2 file I/O and filters ¥ standard input and output ¥ filters ¥ using read and write ¥ opening and closing files ¥ low-level I/O vs. stdio ¥ mixing them using it
  • 14. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/11 input and output each running program has numbered input/outputs: 0 Ð standard input ¥ often used as input if no file is given ¥ default input from the user terminal 1 Ð standard output ¥ simple program's output goes here ¥ default output to the user terminal 2 Ð standard error ¥ error messages from user ¥ default output to the user terminal these numbers are called file descriptors ¥ used by system calls to refer to files 0 1 2 input output errors
  • 15. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/12 redirecting from the shell default input/output is user's terminal redirection to or from files: r command fred Ð standard input from file 'fred' 0 1 2 output errors 'fred' r command harry Ð standard output goes to file 'harry' 0 1 2 input errors 'harry' Ð file is created if it doesn't exist N.B. C shell prevents overwriting r command harry Ð similar, but appends to end of 'harry'
  • 16. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/13 redirection of standard error r command 2errlog Ð standard error goes to file 'errlog' 0 1 2 input output 'errlog' r command 2errlog Ð standard error appends to end of 'errlog' r command 21 Ð standard error goes to current destination of standard output 0 1 2 input output errors
  • 17. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/14 filters ¥ some commands only work on named files: e.g. copying Ð cp from-file to-file ¥ many take standard input as default cat, head, tail, cut, paste, etc. ¥ these are called filters Ð very useful as part of pipes ¥ also very easy to program! donÕt have to worry about r command line arguments r opening or closing files ¥ just read-process-write
  • 18. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/15 read write ret = read(fd,buff,len) int fd Ð a file descriptor (int), open for reading char *buff Ð buffer in which to put chars int len Ð maximum number of bytes to read int ret Ð returns actual number read ¥ ret is 0 at end of file, negative for error ¥ buff is not NULL terminated leave room if you need to add Ô0Õ! ret = write(fd,buff,len) int fd Ð a file descriptor (int), open for writing char *buff Ð buffer from which to get chars int len Ð number of bytes to write int ret Ð returns actual number written ¥ ret is negative for error, 0 means Òend of fileÓ ret may be less than len e.g. if OS buffers full * should really check and repeat until all gone * ¥ buff need not be NULL terminated if buff is a C string, use strlen to get its length N.B. Both may return negative after interrupt (signal)
  • 19. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/16 example – file translation ¥ a Macintosh → UNIX text file conversion program main() { char buf[256]; for(;;) { int i int n = read(0,buf,256); Œ if ( n = 0 ) exit(-n); y for ( i=0; in; i++ ) if ( buff[i] == ‘r’ ) z buff[i] = ‘n’; write(1,buf,n); { } exit(0); } x read from file descriptor 0 Ð standard input buffer size is 256 bytes number of bytes read goes into n y end of file (0) or error (n0) both exit the -n means that end of file gives a zero exit code z Macintosh uses carriage return 'r' to end lines UNIX uses newline 'n' { writing to 1 Ð standard output remember only write n bytes not 256!
  • 20. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/17 opening and closing files #include fcntl.h int fd = open(name,flags) char *name Ð name of the file to open int flags Ð read/write/append etc. int fd Ð returns a file descriptor ¥ in simple use flags is one of: O_RDONLY Ð read only (0) O_WRONLY Ð write only (1) O_RDWR Ð read and write (2) but can ÔorÕ in other options ¥ negative result on failure r file doesnÕt exist r do not have permissions ¥ closing files is simpler! int res = close(fd) int fd Ð an open file descriptor int ret Ð returns: 0 OK -1 failed
  • 21. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/18 low-level I/O vs. stdio ¥ why use low-level I/O? r less layers ≈ more efficient r more control Ð e.g. random access r sometimes have to Ð e.g. networks ¥ can you mix low-level I/O and stdio? yes $ with care! ¥ different files/devices no problem ¥ same file $ stdio is buffered printf(hello ); write(1,there ,6); printf(worldn); ¯ output: there hello world
  • 22. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/19 Hands on write a simple cypher filter: cypher.c the filter should copy standard input to standard output adding 1 to each byte: a→b, b→c, c→d, d→e, etc. it will be similar to the Mac→UNIX translator except that the loop should add 1 rather than replace carriage returns with line feeds to make a better cypher, you could add a different number or have a 256 byte array to act as the cypher compile either with ÔccÕ Ð the old KR C compiler: cc -o cypher cypher.c or with ÔaccÕ Ð the ANSI C compiler: cc -o cypher cypher.c
  • 23. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/20 UNIXSystems Programming I Session 3 makefiles and arguments ¥ make ¥ argv and argc ¥ environment variables using it
  • 24. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/21 make ÔmakeÕ is a UNIX command which: ¥ automates program construction and linking ¥ tracks dependencies ¥ keeps things up-to-date after changes to use it: r construct a file with rules in it you can call it anything, but ÔmakefileÕ is the default r run ÔmakeÕ itself make target – (uses the default makefile) make -f myfile target – (uses the rule file myfile) either rebuilds the program ÔtargetÕ if necessary ¥ each makefile consists of: r definitions r rules ¥ rules say how one thing depends on another they are either: r specific Ð e.g. to make mail-client do this ... r generic Ð e.g. to make any Ô.oÕ from its Ô.cÕ ... make is also available in many other programming environments
  • 25. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/22 makefile format Definitions ¥ general form: variable = value ¥ example: SDIR = tcp MYLIBS = $(SDIR)/lib N.B. one variable used in another's definition ¥ make variables are referred to later using $ e.g.$(SDIR), $(MYLIBS) ¥ expanded like #defines or shell variables (some versions of make will expand shell variables also) Rules (just specific rules) ¥ general form: target : dependent1 dependent2 ... command-line ↑ N.B. this must be a tab ¥ example: myprog: myprog.o another.o cc -o myprog myprog.o another.o $(MYLIBS) this says: to make myprog you need myprog.oandanother.o if either of them is newer than myprog rebuild it using the then rebuild it using the command: Òcc -o myprog ...Ó
  • 26. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/23 argc argv int main( int argc, char **argv ) ... or: int main( int argc, char *argv[ ] ) ... ¥ one of the ways to get information into a C program ¥ in UNIX you type: myprog a b c d the program gets: argc = 4 Ð length of argv argv[0] = myprog Ð program name argv[1] = a argv[2] = b c Ð single second argument argv[3] = d argv[4] = NULL Ð terminator N.B. r DOS is identical (except argv[0] is NULL early versions) r argc is one less than the number of arguments! ¥ other ways to get information in (UNIX DOS): r configuration file (known name) r standard input r environment variables using getenv() or (UNIX only) third arg to main: main(int argc, char **argv, char **envp)
  • 27. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/24 environment variables ¥ set of name=value mappings ¥ most created during start-up (.profile, .login etc.) setting a variable from the shell: myvar=hello var2= a value with spaces needs to be quoted export myvar ¥ no spaces before or after '=' sign ¥ variables need to be exported to be seen by other programs run from the shell ¥ in C shell: set name=val and no export listing all variables from the shell: $ set HOME=/home/staff2/alan myvar=hello PATH=/local/bin:/bin:/local/X/bin USER=alan . . . $
  • 28. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/25 environment variables – 2 ¥ accessing from a program Ð 3 methods x extra argument to main main(int argc,char **argv,char **envp) y global variable extern char **environ z system function char *value = getenv(name); ¥ both x and y give you a structure similar to argv r a null terminated array of strings r but environment strings are of the form name=value ¥ the getenv function z rather different r fetches the value associated with name r returns NULL if name not defined ¥ also a putenv function r only available to this process and its children r not visible to the shell that invoked it
  • 29. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/26 Hands on write a program to produce a list of arguments as in the 'argc argv' slide the core of your program will look something like: for(i=0; iargc; i++) printf(argv[%d] = %sn,argv[i]); if you use ÔccÕ then the ÔmainÕ program begins: main(argc,argv) int argc; char **argv; the slide shows the ANSI C declaration do a similar program for environment variables
  • 30. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/27 UNIXSystems Programming I Session 4 file manipulation ¥ creating new files ¥ ÔdeletingÕ files ¥ linking to existing files ¥ symbolic links ¥ renaming files ¥ creating/removing directories using it
  • 31. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/28 creating files int fd = creat(path,mode) char *path Ð the name/path of the (new) file int mode Ð permissions for the new file int fd Ð returns a file descriptor ¥ file is created if it doesnÕt exist ¥ if it already exists, acts like an open for writing ¥ negative return on failure ¥ mode sets the initial permissions, e.g. mode = S_RWXUSR | S_IRGRP | S_IXGRP | S_IXOTH Ð read/write/execute for user (S_RWXUSR) Ð read/execute for group (S_IRGRP | S_IXGRP) Ð execute only for others (S_IXOTH) ¥ when created, file descriptor is open for writing f even if permissions do not include write access ¥ alternative Ð use open with special flags: int fd = open( path, O_WRONLY|O_CREAT|O_TRUNC, mode ) ¥ O_CREAT flag says Òcreate if it doesnÕt existÓ ¥ note extra mode parameter
  • 32. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/29 deleting files ¥ UNIX rm command ÔdeletesÕ files ¥ it uses the unlink system call int res = unlink(path) char *path Ð the name/path of the file to remove int mode Ð permissions for the new file int res Ð returns an integer 0 Ð OK -1 Ð fail ¥ doesnÕt necessarily delete file! ¥ but neither does rm ¥ UNIX filenames are pointers to the file ¥ there may be more than one pointer
  • 33. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/30 hard links ¥ linking to an existing file: r shell Ð ln tom fred r system call Ð link(tom,fred) ¥ file tom must already exist ¥ fred points to the same file as tom tomfred ¥ unlink simply removes a pointer ¥ file destroyed only when last link goes
  • 34. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/31 symbolic links ¥ ÔhardÕ links are limited: r cannot link to a different disk r only one link to a directory (actually not quite true as there are all the Ò..Ó links) ¥ symbolic links are more flexible r shell Ð ln -s tom fred r system call Ð symlink(tom,fred) ¥ tom need not exist ¥ fred points to the name ÔtomÕ Ð an alias tomfred
  • 35. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/32 links and updates cp fred tom ln fred tom ln -s fred tom fred tom tomfred tomfred ¥ update file tom fred tom tomfred tomfred ¥ delete file tom Ð unlink(tom) fred tom tomfred tomfred ¥ what is in fred? fred fred ?fred
  • 36. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/33 renaming files int res = rename(path1,path2) char *path Ð the name/path of the (new) file int fd Ð returns a file descriptor ¥ system call used by UNIX mv command ¥ only possible within a file system x path2 is unlinked y path2 is linked to the file pointed to by path1 z path1 is unlinked ¥ result: path2 points to the file path1 used to point to e.g. rename(fred,tom) fred tom fred tom
  • 37. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/34 directories ¥ special system calls to create and remove directories int res = mkdir(path,mode) char *path Ð the path of the new directory int mode Ð permissions for the new directory int res Ð returns an integer 0 Ð OK -1 Ð fail ¥ mkdir rather like creat int res = rmdir(path) char *path Ð the path of the directory to remove int res Ð returns an integer 0 Ð OK -1 Ð fail ¥ unlike unlink does delete directory! ¥ but only when empty
  • 38. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/35 Hands on rm has various options so it is hard to delete files with strange names such as Ô-bÕ Ð I know I got one once! write a program raw-rm.c which has one command line argument, a file to delete, and performs an unlink system call on it modify raw-rm so that it can take a list of files: raw-rm tom dick harry write a version of mv that doesnÕt use the rename system call, but only link and unlink N.B. if you get the order wrong youÕll loose the file!
  • 39. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/36 UNIXSystems Programming I Session 5 terminal I/O ¥ terminals are just files? ¥ tty drivers ¥ stty and gtty ¥ handling input ¥ the termcap database ¥ toolkits using it
  • 40. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/37 terminals are easy? ¥ terminal is default input/output ¥ read and write just like any file r use read/write system calls r or stdio ¥ interactive programs Ð a doddle printf(what is your name? ); gets(buff); printf(hello %s how are you todayn,buff); get line editing for free $ paper-roll model of interaction r only see user input in whole lines ¥ terminals not quite like other files: r write anywhere on screen r cursor movement r special effects (flashing, colours etc.) r non-standard keys: ctrl, alt, F3 etc.
  • 41. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/38 tty drivers ¥ never connected directly to terminal ¥ tty driver sits between r does line editing r handles break keys and flow control (ctrl-C, ctrl-, ctrl-S/ctrl-Q) r translates delete/end-of-line chars ¥ not always wanted! your program tty driver UNIX kernal
  • 42. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/39 stty command ¥ control the tty driver from the shell $ stty everything $ stty -echo $ type something Ð no echo $ reset ¥ stty differs between UNIXs! ¥ can control r echoing r parity, stop bits etc. for modems r carriage return / newline mapping r delete key mapping (delete/backspace) r break key activity r line editing . . . and more
  • 43. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/40 gtty stty functions ¥ you can do the same from a program #include sgtty.h int echo_off(tty_fd) int tty_fd; { struct sgttyb buf; gtty(tty_fd,buf); buf.sg_flags = ~ECHO; return stty(tty_fd,buf); } ¥ sg_flags Ð a bitmap of option flags ¥ the sgttyb structure has other fields r line speeds ( sg_ispeed, sg_ospeed) r erase and kill chars ( sg_erase, sg_kill) (word and line delete) ¥ gtty and stty depreciated now r more options available through ioctl r but they are the ÔtraditionalÕ UNIX calls r and simpler!
  • 44. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/41 raw, cbreak and cooked ¥ normal tty processing r echoing of all input r some output translation r line editing r break characters called ÔcookedÕ mode ¥ visual programs do not want this r use stty or ioctl to control ¥ raw mode buf.sg_flags |= RAW; r suppress all input and output processing r echoing still occurs Ð use ECHO bit ¥ cbreak (half-cooked) mode buf.sg_flags |= CBREAK; r as for raw r but break key (ctrl-C) enabled Ì remember to save and reset the mode!
  • 45. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/42 handling input ¥ with raw cbreak r donÕt have to wait for a line end r get characters as they are typed r including delete key ¥ key → input mapping? r simple for ascii keys: A key → ÔaÕ etc. r others → single char: backspace → 0x8 r some → lots i key → ESC [A ¥ prefixes r one key may be a prefix of another! e.g. function key F3 → ESC[19~ escape key → ESC r you read ESC ? how do you know which key ¥ solutions x wait for next character $ could wait a long time! y assume that the whole code is read at once $ not always true z as x but with timeout $ best solution $ introduces delays $ may still fail (swopped out)
  • 46. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/43 termcap ¥ different kinds of terminals r different screen sizes (80x25?) r different capabilities (flashing, underline, ...) r different keyboards r different screen control characters ¥ how do you know what to do? $ write terminal specific code use termcap x environment variable TERM gives terminal type e.g. vt100, vt52 etc. y /etc/termcap database gives capabilities and codes for each type d0|vt100|vt100-am|vt100am|dec vt100: :do=^J:co#80:li#24:cl=50E[;HE[2J:sf=5ED: :le=^H:bs:am:cm=5E[%i%d;%dH:nd=2E[C:up=2E[A: 7 more lines! r each item gives a code/capability e.g. do=^J Ð send ctrl-J to move cursor down co#80 Ð 80 columns
  • 47. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/44 termcap library ¥ read /etc/termcap directly? ¥ termcap library has functions to help cc -o my-vis my-vis.c -ltermcap r tgetent(val,tname) Ð get the info for terminal tname r tgetnum(id) Ð return the number for capability id r tgetflag(id) Ð test for capability id r tgetstr(id) Ð return the string value for id r tgoto(code,col,line) Ð generate a cursor addressing string r tputs(str,lines_affected,output_f) Ð outputs with appropriate padding ¥ not exactly a high-level interface
  • 48. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/45 curses and toolkits ¥ various high-level toolkits available e.g. curses, C-change ¥ curses is the UNIX old-timer! cc -o my-cur my-cur.c -lcurses -ltermcap ¥ many functions including: r initscr() endwin() Ð start and finish use r move(line,col) Ð cursor positioning r printw(fmt, ...) Ð formatted output r mvprintw(line,col,fmt, ...) Ð both together! r mvgetch(l,c), mvgetstr(l,c,buf) Ð read user input r mvinch() Ð read screen r clear(), refresh() Ð clear and refresh screen r cbreak(), nocbreak(), echo(), raw(), Ð setting terminal mode
  • 49. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/46 Hands on use stty at the shell to set echo, cbreak and raw $ cat type a few lines to see what it normally does ^D $ stty cbreak $ cat type a bit ^D $ stty raw $ echo hello use cat to see what codes your terminal produces $ cat type lots of keys and things ^D $ try entering and running the following: #include curses.h main() { initscr(); clear(); mvprintw(10,30,hello world!); move(20,5); refresh(); endwin(); } what happens if you leave out the refresh()call
  • 50. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/47 UNIXSystems Programming I Session 6 signals and time ¥ what are signals ¥ the signal system call ¥ problems of concurrency ¥ finding the time ¥ going to sleep using it
  • 51. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/48 signals ¥ interacting with the world r file/tty input Ð what r signals Ð when ¥ signals happen due to: r errors SIGFPE Ð floating point error SIGSEGV Ð segment violation (usually bad pointer!) r interruptions SIGKILL Ð forces process to die SIGINT Ð break key (ctrl-C) r things happen SIGALRM Ð timer expires SIGCHLD Ð child process has died r I/O event SIGURG Ð urgent data from network SIGPIPE Ð broken pipe
  • 52. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/49 catching signals ¥ default action for signals r some abort the process r some ignored ¥ you can do what you like r so long as you catch the signal r and itÕs not SIGKILL(signal 9) x write the code that you want run int my_handler() { my_flag = 1n”; } y use the signal system call to tell UNIX about it signal(SIGQUIT,my_handler); z when the signal occurs UNIX calls my_handler { when you no longer require a signal to be caught signal(SIGQUIT,SIG_IGN); signal(SIGFPE,SIG_DFL);
  • 53. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/50 care with signals ¥ signal handlers can run at any time int i = 0; int my_handler() { i = i + 1; } main() { signal(SIGINT,my_handler); for(;;) if ( i 0 ) { do_something(); i = i - 1; } } ¥ intention: execute do_something once per interrupt ¥ what actually happens: x interrupt processed (i=1) y do_something executes z main calculates i-1 gets result 0 { before it stores the result . . . . . . another interrupt (i=2) | main stores result (i=0)
  • 54. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/51 working with time ¥ processes need to tell the time r absolute time: 15:17 on Thursday 21st March r elapsed time: that took 3.7 seconds ¥ and time their actions r delays: wait for 5 seconds r alarms: at 11.15pm do the backup ¥ delays easy r sleep(t) system call r waits for t seconds r at least! sleep(5); /* waits for at least 5 seconds */ ¥ cannot guarantee time r other processes may be running r not a real-time operating system ¥ alarms covered in UNIX Systems Programming II
  • 55. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/52 finding the time ¥ UNIX time started on 1st January 1970! ¥ time system call returns seconds 1/1/1970 #include sys/types.h #include sys/time.h time_t t = time(NULL); ¥ ftime gives you milliseconds and timezone too #include sys/timeb.h struct timeb tmb; int res = ftime(tmb); ¥ the process does not run all the time clock gives cpu time used in µsecs long cpu_t = clock(); N.B. times gives you more information about cpu usage
  • 56. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/53 telling the time ¥ users donÕt measure time in seconds since 1/1/1970! ¥ collection of functions to do conversions between four time formats x seconds since 1/1/1970 y struct timeb (from ftime) z struct tm (gives year, day, hour etc.) { ascii representation as C string: Sun Sep 16 01:03:52 1973n x → z localtime, gmtime z → { asctime x → { ctime z → x timelocal, timegm r also dysize(yr) Ð number of days in year yr ¥ local variants give local time gm variants give Greenwich Mean Time ¥ see man 3 ctime for more details
  • 57. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/54 Hands on write a program to see how ÔlazyÕ sleep is! it should: x get the time using both clockandtime y print both z do a sleep(5) { get the times again | and print them run it several times and record the results printing at y adds a delay, modify the above plan to make it right and also get it to print the time elapsed as measured by clockandtime run this version and compare results with the first try the program in the Òcare with signalsÓ slide
  • 58. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/55 UNIXSystems Programming I Session 7 mixing C and scripts ¥ shell scripts ¥ what are they good for? ¥ information shell → C ¥ results C → shell example
  • 59. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/56 shell ¥ the shell is a programming language r data: environment variables (character strings) whole files r control flow: similar + special features r procedures: shell scripts ¥ shell and C: r shell: good at manipulating files and programs $ slow for intensive calculation r C: fast and flexible $ longer development cycle ¥ use them together
  • 60. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/57 shell scripts ¥ shell scripts are files: x starting with: #!/bin/sh y containing shell commands z made executable by chmod a+x ¥ executed using a copy of the shell $ cat my-first-script #!/bin/sh echo hello world $ chmod a+x my-first-script $ my-first-script hello world $
  • 61. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/58 it’s good to talk ¥ shell and C need to communicate ¥ shell → C r standard input: large amounts of data r command line arguments: file names, options r environment variables: long-term preferences settings ¥ C → shell r standard output: large amounts of data r standard error: $ normally only to the user r exit code: success/failure or single number
  • 62. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/59 shell → C ¥ standard input Ð not just files! r single line Ð use echoand pipe echo hello | myprog r lots of lines Ð use HERE file my-prog HERE this is two lines of text HERE ¥ command line arguments r shell pattern matching is great r let it check and pass good args in ¥ environment variables r inwards only!
  • 63. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/60 C → shell ¥ standard output r redirect to file my-prog some-args fred.out r pipe it my-prog some-args | more-progs r or use backquotes! myvar=`my-prog some-args` ¥ exit code r remember: 0 = success r use if, while etc. if my-prog some-args then echo OK else echo failed fi r or use $? my-prog some-args echo returned $?
  • 64. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/61 example the following numc.c is a filter for numbering lines #include stdio.h char buff[256]; main() { int lineno; for ( lineno=1; gets(buff); lineno++ ) printf(%4d: %sn,lineno,buff); } we would like to give it arguments $ numc fred 1: fred’s first line 2: the second line of fred $ too much work! use a shell script weÕll call it num #!/bin/sh case $# in 0) numc; exit 0;; # filter mode esac for i # loops through all arguments do echo; echo ---- $i ---- numc $i done
  • 65. UNIXSystems ProgrammingI Short Course Notes Alan Dix © 1996 I/iii random access ¥ normally read/write are serial r move forward byte by byte through the file ¥ lseek allows random access off_t pos = lseek(fd,offset,flag) int fd Ð an open file descriptor off_t offset Ð number of bytes to seek (negative means back) int flag Ð where to seek from: L_SET Ð beginning of file L_INCR Ð current position L_XTND Ð end of file off_t pos Ð the old position in the file (N.B. off_t is actually a long int!) ¥ moves the I/O position forward or back by offset ¥ finding where you are without moving: r move zero (0L) from current position (L_INCR) r tell function Ð used to be a system call!