slides pratica signals e pipes

Upload: andre-perdigao

Post on 07-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Slides Pratica Signals e Pipes

    1/12

    Department of Informatics EngineeringFCTUCUniversity of Coimbra

    SignalsA signal represents an asynchronous event which an application must(should? can?) process The programmer can register a routine to handle such eventsExamples: The user hits Ctrl+C -7 SIGINT The system requests the application to terminate The program tried to write to a closed channel

    -7 SIGTERM-7 SIGPIPE

    Process

    fi~t~igi~tj;~~dI~~(){~ II process signal~.!. .

  • 8/3/2019 Slides Pratica Signals e Pipes

    2/12

    Signals (2)Signals can be in one of four states: Blocked:Upon arrival, they are stored in a queue until the process unblocks them.Then, they are delivered. Ignored:Upon arrival, they are discarded. It is as if they had never existed. Being Handled:They are redirected to a signal handler which is called. None of the above:Non-handled, non-blocked or ignored signals. Upon arrival, they causeprogram termination.Some signals cannot be ignored or handled (e.g. SIGKILL)When a process starts, signals are on their "default behavior". Some are ignored, most are in the "non-handled, non-blocked norignored state". If a signal occurs, the process will die.

    Basic Signal Routinesprototype of thetypedef void (*sighandler_t)(int); - handler routine

    sighandler_t signal(int signum, sighandler_t handler);Redirects a certain signal (signum) to a handler routine.int kill(pid_t pid, int sig);Sends a signal to a certain process identified by a PID. (Note: if pid is 0,sends to all processes in the current process group.)int pauset):Blocks the process until a signal is received .

    ..............................................................i in t s ig ac ti on () ;i in t s ig pr oc ma sk () ;! in t s ig pe nd in g( );! in t s ig su sp en d( );............................... _ .

    Note: These are therecommended POSIX routines.We are not going to cover themhere. The problem with signalOis that in certain cases itsbehavior is undefined acrosssystems.

  • 8/3/2019 Slides Pratica Signals e Pipes

    3/12

    Handling a signal[~ ~ id ~ ig "i~ t(i~ t~ ig~ ~ ~ ){ .

    char option[2];printf("\n "C pressed. Do you want to abort? ");scanf("%ls", option);if (option[0] = = 'y') {printf("Ok, bye bye!\n");exit(0) ;}

    }int main(){II Redirects SIGINT to sigint()signal(SIGINT, sigint);II Do some work!while (1) {printf("Doing some work ... \n");

    sleep(l);}return 0;}

    Specia l constants in s igna lO

    Isignal(SIGINT, SIG_IGN) IIgnores SIGINT

    Isignal(SIGINT, SIG_DFL) IRestores SIGI NT to its"default" handling

  • 8/3/2019 Slides Pratica Signals e Pipes

    4/12

    Blocking a signal[~ ~ id ~ ig "i~ t(i~ t~ ig~ ~ ~ ){ .}

    int main(){ s ig na l( SI GI NT , s ig in t) ;s ig se t_ t b lo ck _c tr lc ;sigemptyset (&block ctrlc);sigaddset (&block_ctrlc, SIGINT);II Do some work!while (1) {

    sigprocmask (SIG BLOCK, &block ctrlc, NULL);printf("Doing some work ... \n");sleep(5);printf("End of job.\n");sigprocmask (SIG_UNBLOCK, &block_ctrlc, NULL);}return 0;

    }

    The problem with signals They make programming extremely hard

    It's completely asynchronous: you never know when youare going to get a signal This means that you have to protect all calls!

    After calling a standard function, it may return -1indicating an error errno==EINTR means that a certain routine wasinterrupted and has to be tried again.

    Other routines return other things. It you are using signals, you have to protect them againstall that!

  • 8/3/2019 Slides Pratica Signals e Pipes

    5/12

    The problem with signals (2)For instance, simply to try to read a "structperson" from disk ...struct person p;int n, total = 0;while (total < sizeof(p)){ n = read(fd, (char*)p + total, sizeof(p) -total);if (n == -1){ if (errno == EINTR)continue;else{II True error!

    }}total+= n; And you have to do something like thisfor all calls being done in your program!

    Sending a signalIt's just a question of calling killO with the PIDofthe target process ...v oi d m as te r( pi d_ t p id _s on ){ p ri nt f( "Ma st er s le ep in g f or a w hi le . ..\ n" );s l ee p( 3) ;p ri nt f( "Ma st er s ay s: He ll o s on !\ n" );k il l ( pi d_ so n. S IG US Rl );}in t main( ) {pi d_t s on;II Cr eate s a wor ker proc essif ((s on=f ork( )) == 0) {w or k er ( ) ;exit(0);

    }II T he ma sterm a st er ( so n ) ;wait (NULL);r etu r n 0;

    }

  • 8/3/2019 Slides Pratica Signals e Pipes

    6/12

    T he code of th e child process . .., .void dady_call(int signum){printf("Dady has just called in!\n");

    }void worker(){II Redirect "user signal 1" to a handler routinesignal(SIGUSR1, dady_call);II Do some workprintf("Child process, life is good ... \n");for (int i=0; i

  • 8/3/2019 Slides Pratica Signals e Pipes

    7/12

    BewareSignal numbers vary across operating systems andarchitectures. Don't rely on them, use symbolicconstants "man 7 signal"

    Signal Va l u e Ac t i o n Comment

    S I G B U SS I G P O L LS I G P R O FSIGSYSSIGTRAPS I G U R GS I G U TA L R MSIGXCPUSIGXFSZS I G I D TS I G E M TS I G S T K F L TS I G I DS I G C L DSIGPWIISIGHIFOS I G L O S TSIGWHiCHS I G U I 1 U S E D

    IH. "I.1H CUlTTermTerMCoreCoreI g nTermCoreC o r e

    Hu x I:JTUr (1) (1 MI:mur'IJ ,II:I:I:SS)Po] l ab l c event (Sys U). Synonym of S]G]OProf iIi s timer" e)

  • 8/3/2019 Slides Pratica Signals e Pipes

    8/12

    S tre am mode o f c ommun ic atio nPipes and Named Pipes allow processes to communicate using"streams of data" A "pipe" is a connection between two processes. You can sendthings through the pipe, you can try to receive things from thepipe.

    r " r ". pipe ,................ . .. .. .write() : ) ) read()\.................. .................\... ~ \... ~

    A pipe acts like a synchronous finite buffer. If a process tries to write to a pipe that is full, it blocks If a process tries to read from a pipe that is empty, it blocks

    PipesProvides for communication amount processes that arehierarchically related (i.e. father-child) Pipes must be created prior to creating child processesWhenever a pipe is created, using pipe(), two file descriptors areopened: one for reading (fd[O]), one for writing (fd[l]) Unused file descriptors should be closed!Pipes are unidirectional

    int fd[2];pipe(fd);

    fd[l] )_fd[O].writi n::-fg...."------" drea mg

  • 8/3/2019 Slides Pratica Signals e Pipes

    9/12

    Example............................................................................................................typedef struct {int a;int b;} n umb er s;II File descriptors for the pipe channeli nt c ha nn el [2] ;( ... )int main () {II Create a pipepipe(channel);II Create the processesif (fork() = = 0) {worker() ;e xi t( 0) ;}master();wait(NULL) ;return 0;

    }

    Example (cont.)void worker() {numbe rs n;

    close(channel[l]);while (1) {r ea d( ch an ne l[ 9] , & n, s iz eo f( nu mb er s) );printf(" [WOR KER ] R eceived (%d,%d) from master to add. R esult=%d\n" ,n .a, n. b , n. a+n .b) ;}

    }void maste r (){ numbe rs n;

    close(channel[0]);while (1) {n.a = rand() % 100;n.b = rand() % 100;

    printf(" [MASTER ] Sending (%d,%d) for WOR KER to add\n", n.a, n.b);w ri te (c ha nn el [l ] , & n, s iz eo f( nu mb er s) );s le ep (2 ) ;}

    ;.: [28]

  • 8/3/2019 Slides Pratica Signals e Pipes

    10/12

    Be care fu l!A pipe is a finite buffer. If you try to write too much too quickly intoit, the process will block until some space clears up.Atomicity is something to be dealt with If you try to write less that PIPE_BUFbytes into a pipe, you areguaranteed that it will be written atomically It you try to write more, you have no guaranties! If severalprocesses are writing at the same time, the writes can beinterleaved Also, when a process tries to read from a pipe, you are notguaranteed that it will be able to read everythingMeaning... You must synchronize your writes when you're writing a lot ofdata! You must ensure that you read complete messages!

    st ruct person p;

    int n, total = 0;while (total < sizeof(p {n = read(fd[01, (char*)p + total, sizeof(p)-total);total+= n;}

    Controlling F ile Descr ip torsEach process has a file descriptor table. By default, entries 0,1 and 2 are: stdin, stdout, stderr.Each time a file is open, an entry is added to this table. Eachtime a file is closed, the corresponding entry becomesavailable.The process descriptor table, in fact, contains only referencesto the OS global file descriptor table.

    o stdin1 stdout2 stderr3 4 f25 f36

    FileDescriptorTable after:open("fl")open("f2")open("f3")close("fl")

  • 8/3/2019 Slides Pratica Signals e Pipes

    11/12

    Contro lling F ile Descrip to rs (2 )Two routines are useful for controlling filedescri ptors: int dup(int fd)Duplicates file descriptor "fd" on the first available

    position of the file descriptor table . int dup2(int fd, int newfd)

    Duplicates file descriptor "fd" on the "newfd" position,closing it if necessary.

    Note that after a file descriptor is duplicated, theoriginal and the duplicate can be usedinterchangeably. They share the file pointers, thebuffers, locks, etc. Careful: Closing one file descriptor doesn't close all otherthat have been duplicated!

    Implementin g a p ip e b etw een two p ro ce ssesImplementing .~between two r

    #include #include is quite easy. I #include int mainOnecessary to 2 {the standard 0 II Create a pipe for associating "ls" with "sort."int fd [2];pipe(fd);one process w if (fork() == 0) {standard inpu II Redi recto stdout to the input. of the pi pe andII close unneeded file descriptorsanother. dup2(fd[1] , fileno(stdout));close (fd [0]);Simple examp close (fd [1]);II Become lssort". execlp("ls", "ls", NULL);}el se {II Redirect stdout to the exit of the pipe and

    Note: closing c II close unneeded file descript .orsdup2(fd[0] , filenoCstdin));close (fd [0]);descriptor doe close (fd [1]);all other that t - II Become sortexeclp("sort", "sort", NULL);duplicated! }

    retu rn 0;}I

    0

  • 8/3/2019 Slides Pratica Signals e Pipes

    12/12

    Resulting in...