© 숙대 창병모 1 제 10 장 신호 (Signal). © 숙대 창병모 2 Contents 1. Signal Concepts 2. signal() 3. Interrupted System Calls 4. kill() /raise() 5. alarm() pause() 6.

Slides:



Advertisements
Similar presentations
Recitation 8: 10/28/02 Outline Processes Signals –Racing Hazard –Reaping Children Annie Luo Office Hours: Thursday 6:00.
Advertisements

Week Fourteen Agenda Announcements Final Exam True/False -100 questions (1 point per question) Multiple Choice - 40 questions (2 points per question)
1 Select and poll and Signals CS 241 April 6, 2012 University of Illinois.
Signals Hua LiSystems ProgrammingCS2690Signals. Topics: Sending Signals -- kill(), raise() Signal Handling -- signal() sig_talk.c -- complete example.
1 Signals COS Goals of Today’s Lecture Overview of signals  Notifications sent to a process  UNIX signal names and numbers  Ways to generate.
CS Lecture 16 Outline Inter-process Communication (IPC) – Pipes – Signals Lecture 161CS Operating Systems 1.
Signal Signal : - is a notification sent to a process to notify it of some event - interrupts whatever the process is doing and force it to handle a signal.
Section A (March 14) Outline Exceptions Process Signals Non-local jumps Reminders Lab4: Due Next Thursday TA: Kun Gao Shamelessly Modified from Minglong.
B. RAMAMURTHY Pag e 1 Task Control: Signals and Alarms Chapter 7 and 8 7/2/2015.
Shells, System Calls, and Signals. What is a Shell? A shell is a command line interface to the operating system – Fetch a command from the user and execute.
CSc 352 Signal Handling in Unix Saumya Debray Dept. of Computer Science The University of Arizona, Tucson
COMP5102 Lecture 4 Operating Systems (OS) Inter-process Communication phones off (please)
Exceptional Control Flow Part II Topics Process Hierarchy Signals CS213.
UNIX Signals Bach 7.2 Operating Systems Course The Hebrew University Spring 2010.
1Reference “Introduction To Unix Signals Programming” in the reference material section Man page – sigprocmask, alarm “Understanding the Linux Kernel”
Operating Systems Chapter 2
The kernel considers each program running on your system to be a process A process lives as it executes, with a lifetime that may be short or long A process.
* POSIX-Defined Signals * Signaling Processes * Signal Mask * sigaction * kill and sigaction * alarm Topics.
Week Fourteen Agenda Announcements Final Exam True/False -100 questions (1 point per question) Multiple Choice - 40 questions (2 points per question)
Agenda  Working with Processes: Purpose Running Programs within same process (execl, execlp, execle, execv, execvp, execve) “Spawning” other process (fork,
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. C H A P T E R S I X Exception Handling.
Chapter 11 Process Management
Unix Process Model Simple and powerful primitives for process creation and initialization. fork syscall creates a child process as (initially) a clone.
Scis.regis.edu ● CS 468: Advanced UNIX Class 5 Dr. Jesús Borrego Regis University 1.
Signals (Chap 10 in the book “Advanced Programming in the UNIX Environment”) Acknowledgement : Prof. Y. Moon at Kangwon Nat’l Univ.
Week Fourteen Agenda Announcements Final Exam True/False -100 questions (1 point per question) Multiple Choice - 40 questions (2 points per question)
Concurrent Processes Processes can concurrently run same program. Processes can concurrently run same program. Processes can start other processes. Processes.
Signals and Signal Processing CIS 370 Lab 7 Umass Dartmouth.
Outline for Today Objectives –Finish discussion of Birrell –UNIX Signals –Eraser Administrative –Spider talk after class.
Signals and Signal Handling. Signals A predefined message sent between two processes or from the kernel to a process, or by a user to a process A software.
Signals (Chap 10 in the book “Advanced Programming in the UNIX Environment”) Acknowledgement : Prof. Y. Moon at Kangwon Nat’l Univ.
NCHU System & Network Lab Lab #8 Signals Operating System Lab.
1 Signals (continued) CS 241 April 9, 2012 University of Illinois.
UNIX Signals * POSIX-Defined Signals * Signaling Processes * Signal Mask * sigaction * kill and sigaction * alarm * Interval Timers * POSIX.1b Timers *
Interprocess Communication Mechanisms. IPC Signals Pipes System V IPC.
UNIX Signals. A UNIX signal corresponds to an event –It is raised by one process (or hardware) to call another process’s attention to an event –It can.
Operating Systems Recitation 4, April th, 2002 Signals.
Signals. Introduction r A signal is a mechanism for notifying a process that an event has occurred. m When a signal is sent to a process is normal execution.
CSC Advanced Unix Programming, Fall, 2008 Welcome back to UNIX System Programming! Monday, September 22, class 5.
1 UNIX System Programming Signals. 2 Overview 1. Definition 2. Signal Types 3. Generating a Signal 4. Responding to a Signal 5. Common Uses of Signals.
Today’s topic Environment variables Signal. The list of environment variables –try ‘env’ –Environment variables can be defined in shell setenv DISPLAY.
Linux/UNIX Programming APUE (Signals) [Ch. 10] 최미정 강원대학교 컴퓨터과학전공.
Today’s topics Signals and how to control the program behavior in handling signals. Terminal I/O.
ACCESS CONTROL. Components of a Process  Address space  Set of data structures within the kernel - process’s address space map - current status - execution.
S -1 Processes. S -2 wait and waitpid (11.2) Recall from a previous slide: pid_t wait( int *status ) wait() can: (a) block; (b) return with status; (c)
1 Lecture 19: Unix signals and Terminal management n what is a signal n signal handling u kernel u user n signal generation n signal example usage n terminal.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Signals.
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo1 Signals.
Process Relationships Chien-Chung Shen CIS/UD
Operating Systems Summer Semester 2011 Practical Session 2, Signals 1.
Operating Systems Inter-Process Communication Signals Moti Geva
UNIX signals.
G.Jyostna.
Signals What is a Signal?
Linux/UNIX Programming
Task Control: Signals and Alarms Chapter 7 and 8
Unix Process Management
제11장 프로세스 시스템 프로그래밍 2011 가을 숙명여대 창병모.
Linux/UNIX Programming
Exceptional Control Flow Part II
Exceptional Control Flow
Shells, System Calls, and Signals
CSC Advanced Unix Programming, Fall 2015
제11장 프로세스 관리.
Signals Tanzir Ahmed CSCE 313 Fall 2018.
Exceptional Control Flow
Inter-Process Communication ENCE 360
Task Control: Signals and Alarms Chapter 7 and 8
Linux/UNIX Programming
Signals.
Presentation transcript:

© 숙대 창병모 1 제 10 장 신호 (Signal)

© 숙대 창병모 2 Contents 1. Signal Concepts 2. signal() 3. Interrupted System Calls 4. kill() /raise() 5. alarm() pause() 6. abort()/sleep() 7. Job-Control Signals

© 숙대 창병모 Signal Concepts

© 숙대 창병모 4 Signals Signals are software interrupts from unexpected events a floating-point error a power failure an alarm clock the death of a child process a termination request from a user (Ctrl-C) a suspend request from a user (Ctrl-Z) Process Signal #8

© 숙대 창병모 5 Predefined signals 31 signals /usr/include/signal.h Every signal has a name begin with 'SIG' SIGABRT: abort signal from abort() SIGALRM: alarm signal from alarm() Actions of the default signal handler terminate the process and generate a core(dump) ignores and discards the signal(ignore) suspends the process (suspend) resume the process

© 숙대 창병모 6 Signal Generation Terminal-generated signals CTRL-C  SIGINT CTRL-Z  SIGSTP signal Hardware exceptions generate signals divide by 0  SIGFPE invalid memory reference  SIGSEGV kill() sends any signal to a process or process group need to be owner or superuser Software conditions SIGALRM: alarm clock expires SIGPIPE: broken pipe SIGURG: out-of-band network data

© 숙대 창병모 7 Unix Signals SIGART generated by calling the abort function. SIGALRM generated when a timer set with the alarm expires. SIGCHLD Whenever a process terminates or stops, the signal is sent to the parent. SIGCONT This signal(job-control) sent to a stopped process when it is continued. SIGFPE signals an arithmetic exception, such as divide-by-0, floating point overflow, and so on SIGHUP disconnect detected, session leader terminates

© 숙대 창병모 8 Unix Signals SIGILL when the process has executed an illegal hardware instruction SIGINT generated by the terminal driver when we type the interrupt key and sent to all processes in the foreground process group SIGIO indicates an asynchronous I/O event SIGKILL can’t be caught or ignored. a sure way to kill any process. SIGPIPE If we write to a pipeline but the reader has terminated, SIGPIPE is generated

© 숙대 창병모 9 Unix Signals SIGSEGV indicates that the process has made an invalid memory reference SIGSTOP This signal(job-control) stops a process and can’t be caught or ignored SIGSYS signals an invalid system call SIGTERM the termination signal sent by the kill(1) command by default. SIGTSTP Cntl-Z from the terminal driver which is sent to all processes in the foreground process group.

© 숙대 창병모 10 Unix Signals SIGTTIN generated by the terminal driver when a background process tries to read from its controlling terminal SIGTTOU generated by the terminal driver when a background process tries to write to its controlling terminal SIGPWR related to power failure. (read the book for the detail) SIGQUIT generated by the terminal driver when we type quit key and sent to all foreground processes SIGUSR1, SIGUSR2 user-defined signals for use in application programs

© 숙대 창병모 11 Handling of signals Action Process has to tell the kernel “if and when this signal occurs, do the following.” 3 kinds of actions Ignore the signal all signals can be ignored, except SIGKILL and SIGSTOP Catch the signal Call a function of ours when a signal occurs. The default action most are to terminate process

© 숙대 창병모 System call signal()

© 숙대 창병모 13 signal( ) Signal handler 등록 하나의 signal 에 대한 hanlder 함수를 등록한다. signal(int signo, void (*func)( ))) specify the action for a signal signo → func func SIG_IGN SIG_DFL user-defined function return the previous signal handler function

© 숙대 창병모 14 #include /* sigusr.c */ static void sig_usr(int signo) /* argument is signal number */ { if (signo == SIGUSR1) printf("received SIGUSR1\n"); else if (signo == SIGUSR2) printf("received SIGUSR2\n"); else perror("received signal %d\n", signo); return; } int main(void) { if (signal(SIGUSR1, sig_usr) == SIG_ERR) perror("can't catch SIGUSR1"); if (signal(SIGUSR2, sig_usr) == SIG_ERR) perror("can't catch SIGUSR2"); for ( ; ; ) pause( ); } Example: sigusr.c

© 숙대 창병모 15 sigusr.c: Results $ a.out & start process in background [1] 4720 job number & process ID $ kill –USR send SIGUSR1 received SIGUSR1 $ kill –USR send SIGUSR2 received SIGUSR2 $ kill 4720 send SIGTERM [1] + Terminated a.out &

© 숙대 창병모 16 Program Startup When a process is forked, the child inherits the parent’s signal actions. When a program is exec ed the action of all signals  default action or ignore

© 숙대 창병모 17 Signal handling: Background process Background process Shell sets the action of interrupt and quit signals in background to be ignored Catches the signals in foreground process int sig_int(), sig_quit(); if (signal(SIGINT, SIG_IGN) != SIG_IGN) signal(SIGINT, sig_int); if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) signal(SIGQUIT, sig_quit);

© 숙대 창병모 SIGCHLD

© 숙대 창병모 19 SIGCHLD Whenever a process terminates or stops, the signal is sent to the parent.

© 숙대 창병모 20 Example: Time Limit #include int delay; childHandler( ); int main(int argc; char *argv[ ];) { int pid; signal(SIGCHLD,childHandler); pid = fork(); if (pid == 0) { execvp(argv[2], &argv[2]); perror(“Limit”); } else { sscanf(argv[1], “%d”, &delay); sleep(delay); printf(“Child %d exceeded limit and is being killed\n, pid); kill(pid, SIGINT); } }

© 숙대 창병모 21 Example: Time Limit childHandler( ) /* Executed if the child dies before the parent */ { int childPid, childStatus; childPid = wait(&childStatus); printf(“Child %d terminated within %d seconds\n”, childPid, delay); exit(0); } Usage %limit 5 ls %limit 4 sleep 100

© 숙대 창병모 kill()/raise()

© 숙대 창병모 23 kill() / raise() kill sends a signal to a process or a group of process raise allows a process to send a signal to itself #include int kill(pid_t pid, int signo); int raise(int signo); Both return: 0 if OK, 1 on error

© 숙대 창병모 24 kill() pid > 0 : signal to the process whose process ID is pid pid == 0 : signal to the processes whose process group ID equals that of sender pid < 0 : signal to the processes whose process group ID equals abs. of pid pid == -1 : POSIX.1 leaves this condition unspecified (used as a broadcast signal in SVR4, 4.3+BSD)

© 숙대 창병모 25 kill() Permission to send signals The superuser can send a signal to any process The user ID of the sender == the user ID of the receiver SIGCONT can be sent to any member process of the same session NULL signal signo == 0 Sent with kill for error checking e.g. to check if a process exists If the process doesn’t exist, kill returns –1

© 숙대 창병모 alarm()

© 숙대 창병모 27 alarm() alarm() sets a timer to expire at a specified time when timer expires, SIGALRM signal is generated, default action of the signal is to terminate the process. only one alarm clock per process previously registered alarm clock is replaced by the new value return # of sec. left for the previous alarm alarm(0) a previous unexpired alarm is cancelled #include unsigned int alarm (unsigned int seconds); Returns: 0 or number of seconds until previously set alarm

© 숙대 창병모 28 pause() suspends the calling process until a signal is caught. returns only if a signal handler is executed and that handler returns. #include int pause (void); Returns: -1 with errno set to EINTR

© 숙대 창병모 29 alarm: timeout on blocking operation Timeout A read operation on a "slow" device can block for a long time An upper time limit can be imposed using the alarm function and SIGALRM

© 숙대 창병모 30 #include /* read1.c */ static void sig_alrm(int signo) { return; /* nothing to do, just return to interrupt the read */ } int main(void) { int n; char line[MAXLINE]; if (signal(SIGALRM, sig_alrm) == SIG_ERR) perror("signal(SIGALRM) error"); alarm(10); if ( (n = read(STDIN_FILENO, line, MAXLINE)) < 0) perror("read error"); alarm(0); write(STDOUT_FILENO, line, n); exit(0); } Timeout

© 숙대 창병모 abort()/sleep()

© 숙대 창병모 32 abort() abnormal program termination This function sends the SIGABRT signal to the process SIGABRT signal handler to perform any cleanup that it wants to do, before the process terminated #include void abort(void); This function never returns

© 숙대 창병모 33 sleep() causes the calling process to be suspended until either The amount of wall clock time has elapsed (returns 0) A signal is caught by the process and the signal handler returns (returns the number of unslept seconds) #include unsigned int sleep(unsigned int seconds) ; Returns: 0 or number of unslept seconds

© 숙대 창병모 34 #include /* sleep1.c */ #include static void sig_alrm(int signo) { return; /* nothing to do, just return to wake up the pause */ } unsigned int sleep1(unsigned int nsecs) { if (signal(SIGALRM, sig_alrm) == SIG_ERR) return nsecs; alarm(nsecs); /* start the timer */ pause(); /* next caught signal wakes us up */ return alarm(0); /* turn off timer, return unslept time */ } Using alarm/pause to implement sleep

© 숙대 창병모 35 sleep1.c: Implementation Problems If the caller of sleep1() already has an alarm set, the alarm is erased by the first call to alarm. Modify the action for SIGALRM Save the action and restore it when we're done Race condition: between alarm & pause the alarm goes off before the pause() the signal handler may be called before pause the called is suspended forever at pause()

© 숙대 창병모 36 #include /* sleep2.c */ #include static jmp_buf env_alrm; static void sig_alrm(int signo) { longjmp(env_alrm, 1); } unsigned int sleep2(unsigned int nsecs) { if (signal(SIGALRM, sig_alrm) == SIG_ERR) return nsecs; if (setjmp(env_alrm) == 0) { alarm(nsecs); /* start the timer */ pause(); /* next caught signal wakes us up */ } return alarm(0); /* turn off timer, return unslept time */ } sleep2.c

© 숙대 창병모 Job Control Signals

© 숙대 창병모 38 Job-Control Signals A program that manages the terminal needs to handle job-control signals When type Control-Z (suspend Character), SIGTSTP sent to all foreground processes. SIGCHLD : Child process has stopped or terminated SIGCONT : Continue process, if stopped SIGSTOP : Stop signal (can’t be caught or ignored) SIGTSTP : Interactive stop signal SIGTTIN : Read from control terminal by background processes SIGTTOUT: Write to control terminal by background processes

© 숙대 창병모 39 Example: Suspending and Resume #include main( ) { int pid1, pid2; pid1 = fork( ); if (pid1 == 0) { while(1) { printf(“pid1 isalive\n”); sleep(1); } pid2 = fork( ); if (pid2 == 0) { while (1) { printf(“pid2 is alive\n”); sleep(1); } } sleep(3);kill(pid1, SIGSTOP); sleep(3);kill(pid1, SIGCONT); sleep(3);kill(pid1, SIGINT); kill(pid2, SIGINT); }