Lecture Eleven - PowerPoint PPT Presentation

About This Presentation
Title:

Lecture Eleven

Description:

infp = popen('ls -l', 'r'); /* equivelant to ls -l | thisprogram ... while ( ( c = getc(infp)) != EOF) fprintf(outfp, '%c', c); pclose(infp); pclose(outfp) ... – PowerPoint PPT presentation

Number of Views:94
Avg rating:3.0/5.0
Slides: 46
Provided by: john51
Learn more at: https://www.cse.scu.edu
Category:
Tags: eleven | infp | lecture

less

Transcript and Presenter's Notes

Title: Lecture Eleven


1
Lecture Eleven
  • Unix Programming System Calls

2
Client-Server Model
  • An application model consisting of multiple
    concurrent processes, 1 server process and n
    client procesesses.
  • The server process provides support services to
    the clients
  • The clients contains the main application logic.

3
Client-Server Model
4
Direct Access I/O
  • Avoid sequentially scan through a file
  • int fseek(fp, offset, mode)
  • FILE fp
  • int offset / in bytes /
  • in mode / 0 (SEEK_SET) -- set position to
    offset.
  • 1 (SEEK_CUR) -- set pos to
    (current pos) offset.
  • 2 (SEEK_END) -- set pos to
    EOFoffset
  • fp fopen("myfile", "r")

5
Direct Access I/O
  • if (fseek(fp, nsizeof(record), 0) ! 0)
  • perror("cant seek")
  • return
  • Use with
  • fread((char )record, sizeof(record), 1, fp)
  • / record represents an array. Read a
    record. Return of recs read /
  • fwrite((char) record, sizeof(record), 1, fp)
  • / return written /

6
File Property
  • include ltsys/stat.hgt
  • int stat (Path, Buffer )
  • const char Path
  • struct stat Buffer
  • int fstat (FileDescriptor, Buffer)
  • int FileDescriptor
  • struct stat Buffer

7
Structure stat
  • struct stat
  • mode_t st_mode / File mode /
  • short st_nlink / Number of links /
  • uid_t st_uid / User ID of the
    file's owner /
  • gid_t st_gid / Group ID of the
    file's group /
  • off_t st_size / File size in bytes
    /
  • time_t st_atime / Time of last access /
  • time_t st_mtime / Time of last data
    modification /

8
Define Game Board
  • / board.h /
  • typedef enum Blank, Red, Blue CellStatus
  • typedef struct
  • CellStatus board9
  • char redPlayer65
  • char bluePlayer65
  • GameBoard

9
Manipulate Game Board
  • / board.c /
  • include ltstdio.hgt
  • include ltstrings.hgt
  • include "board.h"
  • static int newGameNumber()
  • int r
  • / to do /
  • return r

10
Manipulate Game Board
  • int addNewGame(char redPlayer, char bluePlayer,
    int boardSize)
  • int i
  • GameBoard game
  • if (redPlayer NULL bluePlayer NULL
    boardSize lt 3)
  • return -1 / invalid input /
  • for (i 0 i lt 9 i)
  • game.boardi Blank

11
Manipulate Game Board
  • strcpy(game.redPlayer,redPlayer)
  • strcpy(game.bluePlayer,bluePlayer)
  • static int findGameBoard(int number, GameBoard
    game )
  • / to do /

12
Manipulate Game Board
  • static int won(GameBoard game,CellStatus player)
  • / To Do /

13
Manipulate Game Board
  • static int tie(GameBoard game)
  • int i
  • if (won(game,Red))
  • return 0
  • if (won(game,Blue))
  • return 0
  • for (i 0 i lt game-gtsizegame-gtsize i)
  • if (game-gtboardi Blank)
  • return 0
  • return 1

14
Manipulate Game Board
  • void watch(int gameNumber, int strm)
  • GameBoard game
  • if (findGameBoard(gameNumber,game) lt 0)
  • invalidGame(strm)
  • return
  • gennerateBoardLayout(strm,game)
  • void move(int gameNumber, int x, int y,
    CellStatus player,int strm)
  • GameBoard game
  • if (findGameBoard(gameNumber,game) lt 0)

15
Manipulate Game Board
  • invalidGame(strm)
  • return
  • if (x gt 3 y gt 3 x lt 0 y lt 0)
  • invalidMove(strm)
  • return
  • game.boardx3y player
  • gennerateBoardLayout(strm,game)

16
Calling Command via Shell
  • Use system() . ( include ltstdlib.hgt )
  • Example the list of current directory and print
    it.
  • mail( )
  • FILE fp, fopen() char c
  • system("ls -l gt tmp") / invoking bourne
    shell /
  • fp fopen("tmp", "r")
  • while ( (c getc(fp)) ! EOF)) putchar(c)
  • fclose(fp)

17
Use pipe
  • Use pipe to read the results of a shell command
    or provide input to a shell command.
  • main( )
  • FILE infp, outfp, popen( ) int c
  • infp popen("ls -l", "r") / equivelant to
    ls -l thisprogram /
  • outfp popen("mail qli", "w")
  • while ( ( c getc(infp)) ! EOF)
    fprintf(outfp, "c", c)
  • pclose(infp)
  • pclose(outfp)

18
Access Shell Environment
  • User change the behavior of a program through
    environment variables.
  • char getenv(char name) return a pointer to
    the value of the shell variable named by the
    argument
  • include ltstdlib.hgt
  • main( )
  • char value, getenv( )
  • value getenv("HOME")
  • if (value ! NULL) printf("s\n", value)

19
Process Control
  • A process is the execution of a program.
  • A program by itself is not a process. (A
    university's catalog describes what you need to
    study, but it is not your study. Your study is
    the "process" while the catalog is the program).
  • Multitasking system has more than one processes
    running at a time, to get higher resourse
    utilization and more user frientliness.

20
Process Control
  • Example
  • Mutliple users can use a machine at the same time
    and each has his/her own machine (apperantly).
  • When one process is doing IO (10's of
    milliseconds), the processor can run other
    processes.
  • A process has code (text), static data, dynamic
    data (heap and stack).

21
Process Control (cont.)
  • Process creation/termination
  • fork( ) exit( )
  • execl( ) excelc( ) exclv( ) execv( ) execve( )
    execvp( )
  • Communication/synchronization
  • wait( ) pipe( ) sleep( ) alarm( ) signal( )
    kill( )
  • setjmp( ) longjmp( )
  • The System V IPC
  • msgget( ) msgsnd( ) msgrcv( ) msgctl( )
  • semget( ) semop( ) semctl( )
  • shmget( ) shmat( ) shmdt( ) shmctl( )

22
fork( )
  • int fork( )
  • creates a new (child) process which is identical
    to the caller (the parent process).
  • the child process inherits
  • the code
  • the environment
  • all signal setting
  • set user and group ids
  • time left one the alarm clock
  • current working directory
  • all open file descriptors (copies)

23
fork()
  • fork() returns -1 if a child cannot be created.
    Otherwise it returns0 -- if the process is the
    childthe process id of the child -- if the
    processs is the parent.

24
fork() ( cont.)
  • Example
  • .
  • if ( (pid fork( )) ! 0 )
  • printf("I am the parent process\n")
  • other stuff
  • wait(status)
  • else
  • printf("I am the child process\n")
  • . other child process code

25
fork() ( cont.)
  • How many new processes will be greated if the
    following sequence is executed fork( )
    fork( )

26
wait( ) and exit( )
  • int wait(int status)
  • wait for a child process to terminate
  • void exit(int status)
  • terminate the calling process and return the
    status code.

27
wait( ) and exit( )
  • If the child process ends with exit( ) system
    call then the second lowest byte of status is set
    to the arg given to exit( ).
  • If the child process ended because of a signal,
    the lowest byte of status contains the singal
    number.

28
Event Detection (Signal)
  • Signals (interrupts) can be sent to processes.
    You can ignore a signal, tak default action on a
    signal, or catch the signal.
  • During the execution of a process an interrupt
    (singal) can be sent to the process by "kill"
    command, by kill( ) system call, and alarm( )
    system call.

29
Event Detection (Signal)
  • If you program does not specify anything about
    signal, the default action will be taken by the
    system, normally termination.
  • You can set up traps to catch the signals and
    invoke your own signal handler routines.

30
Event Detection (Signal)
  • Set a trap (calling signal() function)
  • include ltsignal.hgt
  • main( )
  • .
  • signal(SIGINT, handler)
  • / call hander() if SIGINT arrives /

31
Event Detection (Signal)
  • The handler is a function that you define
    ashandler(int signal) check the signal
    type take action accordingly
  • Upon return from the handler, the execution
    continues from the interrupted point.

32
Event Detection (Signal)
  • You can use signal(SIG???, SIG_IGN) to ignore the
    signal SIG???.In this case your program is not
    disturbed.
  • signal(SIG???, SIG_DFL) take default action.
    Normally terminate.
  • There are about 30 signals. Look at "man 5
    signal". E.g., HUP, INT, KILL, STOP, ALRM, etc.

33
Event Detection (Signal)
  • Example
  • kill -HUP pid
  • Many system daemons catch this signal and
    reinitialize themselves.

34
Event Detection (Signal)
  • User may generate a signal by using kill() and
    alarm() system call
  • int kill(int process_id, int signal_name)
  • kill() function can generate any signal and send
    to the processs specified.

35
Event Detection (Signal)
  • unsigned alarm(int seconds)
  • wait the specified number of seconds and send
    ALRM signal to the process who called this
    function.
  • Example set timeout for a process
  • ..
  • signal(SIGALRM, handletimeout)
  • ..
  • alarm(20)
  • .
  • void handletimeout() .

36
Shared Memory
  • Shared memory allows processes to share a piece
    of memory
  • use semaphores to control the synchronization

37
Shared Memory Example
  • Sever
  • include ltstdio.hgt
  • include ltsys/types.hgt
  • include ltsys/ipc.hgt
  • include ltsys/shm.hgt
  • define SHMKEY ((key_t) 7890) /base value for
    shmem key /
  • define PERMS 0666
  • int shmid

38
Shared Memory Example
  • main()
  • Gameboard game
  • if (shmid shmget(SHMKEY, sizeof(Gameboard),
    PERMS IPC_CREAT)) lt 0)
  • error handling
  • if (game (GameBoard)shmat(shmid,(char)0,0))
    (GameBoard)-1)
  • error handling
  • if (shmdt(game) lt 0)
  • error handling
  • if (shmctl(shmid,IPC_RMID,(struct shmid_ds )0)
    lt 0)
  • error hanlding

39
Shared Memory Example
  • Client
  • include ltstdio.hgt
  • include ltsys/types.hgt
  • include ltsys/ipc.hgt
  • include ltsys/shm.hgt
  • define SHMKEY ((key_t) 7890) /base value for
    shmem key /
  • define PERMS 0666
  • int shmid

40
Shared Memory Example
  • main()
  • Gameboard game
  • if (shmid shmget(SHMKEY, sizeof(Gameboard),
    0)) lt 0)
  • error handling
  • if (game (GameBoard)shmat(shmid,(char)0,0))
    (GameBoard)-1)
  • error handling
  • if (shmdt(game) lt 0)
  • error handling

41
Semaphores
  • A synchronization primitive
  • Oprations on a semaphore are atomic
  • Not Used for exchanging data
  • Let multiple processes/threads synchronize their
    operations
  • lock a file
  • synchronize access to shared memory

42
Semaphore Example
  • include ltsys/types.hgt
  • include ltsys/ipc.hgt
  • include ltsys/sem.hgt
  • define SEMKEY 123456L
  • define PERMS 0666
  • static struct sembuf op_lock2
  • 0,0,0, / wait for sem 0 to become 0 /
  • 0,1,SEM_UNDO / then increment sem 0
    by 1 /

43
Semaphore Example
  • static struct sembuf op_unlock1
  • 0,-1,IPC_NOWAIT SEM_UNDO / decrement
    sem 0 by 1 /
  • int semid -1
  • void lockResource()
  • if (semid semget(SEMKEY,1,IPC_CREAT PERMS))
    lt 0)
  • error handling
  • if (semop(semid,op_lock0,2) lt 0)
  • error handling

44
Semaphore Example
  • void unlockResource()
  • if (semop(semid,op_unlock0,1) lt 0)
  • error handling

45
Communicating Through Sockets
Machine A
Machine B
listen
Network
Write a Comment
User Comments (0)
About PowerShow.com