Linux/UNIX Programming APUE (Signals) [Ch. 10] 최미정 강원대학교 컴퓨터과학전공.

Slides:



Advertisements
Similar presentations
Week Fourteen Agenda Announcements Final Exam True/False -100 questions (1 point per question) Multiple Choice - 40 questions (2 points per question)
Advertisements

Page 1 Task Control: Signals and Alarms Havilland and Salama’s Unix Systems Programming B. Ramamurthy.
Page 1 Task Control: Signals and Alarms Chapter 7 and 8 B. Ramamurthy.
CS Lecture 17 Outline Named pipes Signals Lecture 17
Signals Hua LiSystems ProgrammingCS2690Signals. Topics: Sending Signals -- kill(), raise() Signal Handling -- signal() sig_talk.c -- complete example.
UNIX IPC CSE 121 Spring 2003 Keith Marzullo. CSE 121 Spring 2003Review of Concurrency2 Creating a UNIX process A process is created by making an exact.
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.
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)
Carnegie Mellon 1 Processes, Signals, I/O, Shell Lab : Introduction to Computer Systems Recitation 9: 10/21/2013 Tommy Klein Section B.
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)
UNIX Socket Programming CS 6378 Project Reference Book: Unix Network programming: Networking APIs: Sockets and XTI (2nd edition), Prentice Hall >> Threads.
Concurrent Processes Processes can concurrently run same program. Processes can concurrently run same program. Processes can start other processes. Processes.
제 11 장 프로세스 시스템 프로그래밍 1. Objectives Process Start and Exit Create a child process Execute a new program within a process Signal System boot 2.
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 *
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.
KUKUM Real Time System Module #3 POSIX programming Lecture 2.
© 숙대 창병모 1 제 10 장 신호 (Signal). © 숙대 창병모 2 Contents 1. Signal Concepts 2. signal() 3. Interrupted System Calls 4. kill() /raise() 5. alarm() pause() 6.
Today’s topic Environment variables Signal. The list of environment variables –try ‘env’ –Environment variables can be defined in shell setenv DISPLAY.
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.
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
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:

Linux/UNIX Programming APUE (Signals) [Ch. 10] 최미정 강원대학교 컴퓨터과학전공

UNIX System Programming Page 2 Signals Signals are software interrupts from unexpected events an illegal operation (e.g., divide by 0) 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) APUE (Signals) Process Signal #8

UNIX System Programming Page 3 Predefined Signals (1/2) 31 signals / usr/include/signal.h (/usr/include/sys/iso/signal_iso.h) See the table in text 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 APUE (Signals)

UNIX System Programming Page 4 Predefined Signals (2/2) /usr/include/sys/iso/signal_iso.h APUE (Signals)

UNIX System Programming Page 5 Signal Generation Terminal-generated signals CTRL-C  SIGINT CTRL-Z  SIGSTP signal Hardware excepts 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 super-user Software conditions SIGALRM: alarm clock expires SIGPIPE: broken pipe SIGURG: out-of-band network data APUE (Signals)

UNIX System Programming Page 6 Handling of Signals Disposition or action: Process has to tell the kernel “if and when this signal occurs, do the following.” Ignore the signal: all signals can be ignored, except SIGKILL and SIGSTOP Catch the signal: Call a function of ours when a signal occurs. Let the default action apply: most are to terminate process APUE (Signals)

UNIX System Programming Page 7 Representative UNIX Signals (1/2) 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 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 SIGILL: indicates that 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. APUE (Signals)

UNIX System Programming Page 8 Representative UNIX Signals (2/2) 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. SIGSEGV: indicates that the process has made an invalid memory reference. (  core dumped) SIGTERM: the termination signal sent by the kill(1) command by default. SIGSTP: Cntl-Z from the terminal driver which is sent to all processes in the foreground process group. SIGUSR1: user defined signal 1 SIGUSR2: user defined signal 2 APUE (Signals)

UNIX System Programming Page 9 signal() Signal Handler 등록 signal(int signo, void(*func)())) specify the action for a signal (signo  func) func −SIG_IGN (ignore) −SIG_DFL (default) −user-defined function Return: the previous func APUE (Signals)

UNIX System Programming Page 10 예제 : alarm1.c (w/o handler) #include // alarm1.c main( ) { alarm(3); printf(“Looping forever …\n”); while (1); printf(“This line should never be executed\n”); } APUE (Signals)

UNIX System Programming Page 11 예제 : alarm2.c (w/ handler) (1/2) #include // alarm2.c #include int alarmFlag=0; void alarmHandler(); main( ) { signal(SIGALRM, alarmHandler); alarm(3); printf("Looping …\n"); while(!alarmFlag) { pause( ); } printf("Loop ends due to alarm signal \n"); } void alarmHandler( ) { printf("An alarm clock signal was received\n"); alarmFlag = 1; } APUE (Signals)

UNIX System Programming Page 12 예제 : alarm2.c (w/ handler) (2/2) 실행 결과 APUE (Signals)

UNIX System Programming Page 13 SIGCHLD Whenever a process terminates or stops, the signal is sent to the parent. 자식 프로세스는 자신이 죽을 때, 부모 프로세스에게 SIGCHLD 를 보낸다. APUE (Signals)

UNIX System Programming Page 14 예제 : timelimit.c (1/3) #include // timelimit.c #include int delay; void childHandler( ); main(int argc, char *argv[]) { int pid; sscanf(argv[1], "%d", &delay); signal(SIGCHLD,childHandler); pid = fork(); if (pid == 0) { // child execvp(argv[2], &argv[2]); perror("Limit"); } else { // parent sleep(delay); printf("Child %d exceeded limit and is being killed\n", pid); kill(pid, SIGINT); } $ timelimit N command // command 를 N seconds 안에 수행하라 ! APUE (Signals)

UNIX System Programming Page 15 예제 : timelimit.c (2/3) 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); } APUE (Signals)

UNIX System Programming Page 16 예제 : timelimit.c (3/3) 실행 결과 APUE (Signals)

UNIX System Programming Page 17 kill(), raise() kill - sends a signal to a process or a group of processes raise - function 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 APUE (Signals)

UNIX System Programming Page 18 kill() pid means 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: unspecified (used as a broadcast signal in SVR4, BSD) Permission to send signals The super-user can send a signal to any process. The real or effective user ID of the sender has to equal the real or effective user ID of the receiver. APUE (Signals)

UNIX System Programming Page 19 alarm() #include unsigned int alarm (unsigned int seconds); Returns: 0 or number of seconds until previously set alarm APUE (Signals) alarm() sets a timer to expire at a specified time in future. 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. if alarm(0), a previous unexpired alarm is cancelled.

UNIX System Programming Page 20 pause() #include int pause (void); Returns: -1 with errno set to EINTR APUE (Signals) suspends the calling process until a signal is caught. returns only if a signal handler is executed and that handler returns. 그냥 종료하던지 (signal handler 가 등록되지 않은 경우 ), signal handler 가 등록된 경우 해당 handler 가 처리를 마친 후 리턴한다.

UNIX System Programming Page 21 예제 : mysleep.c #include // mysleep.c #include static void sig_alrm(int signo) { return; /* nothing to do, just return to wake up the pause */ } unsigned int mysleep(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 */ } APUE (Signals) 상기 mysleep() 함수는 다음과 같은 몇 가지 문제점을 안고 있다. 만일 mysleep() 을 사용하기 이전에 alarm 을 set 한 경우, 앞서의 alarm 이 지워진다. Race condition 이 발생할 수 있다 ( 즉, pause() 가 호출되기 전에 alarm 이 발생할 수 있다.). 상기 문제 해결을 위해서는 보다 견고한 mysleep() 의 구현이 필요하다.  교재 참조 (sleep2.c 등 )

UNIX System Programming Page 22 abort() #include void abort(void); This function never returns APUE (Signals) Causes 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.

UNIX System Programming Page 23 sleep() #include unsigned int sleep(unsigned int seconds) ; Returns: 0 or number of unslept seconds APUE (Signals) This function causes the calling process to be suspended until either The amount of wall clock time specified by second has elapsed (returns 0) A signal is caught by the process and the signal handler returns (returns the number of unslept seconds)