Preview. Process Termination. wait and waitpid() System Call. wait and waitpid() System Call. waitpid() System Call 10/23/2018

Similar documents
Signals. Joseph Cordina

Operating Systems. Threads and Signals. Amir Ghavam Winter Winter Amir Ghavam

System Programming. Signals I

Lesson 3. The func procedure allows a user to choose the action upon receipt of a signal.

Signals. Goals of this Lecture. Help you learn about: Sending signals Handling signals

So far, we know how to create processes. How do we communicate with them? Primary mechanism: signals

Preview. The pause() System Call. The pause() System Call. The signal() System Call 10/18/2017

Operating Systems 2010/2011

Fortran Signal Handling

System Calls and Signals: Communication with the OS. System Call. strace./hello. Kernel. Context Switch

CS240: Programming in C

Princeton University. Computer Science 217: Introduction to Programming Systems. Signals

Process. Signal #8. Signals are software interrupts from unexpected events. a power failure. an alarm clock. the death of a child process

System Calls & Signals. CS449 Spring 2016

System Programming. Signals II

KING FAHD UNIVERSITY OF PETROLEUM AND MINERALS Information and Computer Science Department ICS 431 Operating Systems Lab # 6

Chapter 4 Multithreaded Programming

Process Control. Philipp Koehn. 23 April 2018

PVPSIDDHARTHA INSTITUTE OF TECHNOLOGY

ECE 650 Systems Programming & Engineering. Spring 2018

Signals! Goals of this Lecture! Help you learn about:" Sending signals" Handling signals"

CSE 421: Introduction to Operating Systems

Goals of this Lecture

Signals. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Multitasking. Programmer s model of multitasking. fork() spawns new process. exit() terminates own process

Signals! Goals of this Lecture! Help you learn about:" Sending signals" Handling signals"

CS213. Exceptional Control Flow Part II. Topics Process Hierarchy Signals

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 18

Embedded Systems Programming

Computer Science & Engineering Department I. I. T. Kharagpur. Operating System: CS rd Year CSE: 5th Semester (Autumn ) Lecture VII

Workshop on Inter Process Communication Solutions

Inter Process Communication

Processes & Signals. System Runs Many Processes Concurrently. State consists of memory image + register values + program counter

APPLIED INFORMATICS Processes. Bash characteristics. Command type. Aliases.

Shell Execution of Programs. Process Groups, Session and Signals 1

Programming Assignments will be.. All the PAs are continuous 3 major factors that you should consider

Operating Systems Grado en Informática. Course

CSci 4061 Introduction to Operating Systems. (Advanced Control Signals)

signals Communicating with the OS System call (last lecture) Signal (this lecture) User Process Operating System

Shell and Signals. Computer Organization 3/17/2015. CSC252 - Spring The World of Multiprogramming or Multitasking. Unix Process Hierarchy

Interprocess Communication

ACSC 372 Systems Programming. exec() Functions. Outline

CSC209H Lecture 8. Dan Zingaro. March 4, 2015

CSE 410: Computer Systems Spring Processes. John Zahorjan Allen Center 534

Signals. CSC209: Software Tools and Systems Programming. Furkan Alaca & Paul Vrbik

Process management. What s in a process? What is a process? The OS s process namespace. A process s address space (idealized)

Kernel and processes

CSE 451: Operating Systems Winter Module 4 Processes. Mark Zbikowski Allen Center 476

Advanced Unix/Linux System Program. Instructor: William W.Y. Hsu

COMP 2400 UNIX Tools

Operating Systems. No. 5 ศร ณย อ นทโกส ม Sarun Intakosum

CS 33. Signals Part 1. CS33 Intro to Computer Systems XXII 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Exceptional Control Flow Exists at All Levels of a System. Systemprogrammering 2007 Föreläsning 3 Exceptional Control Flow Part II

Signals. POSIX defines a variety of signal types, each for a particular

Overview. Administrative. * HW 1 grades. * HW 2 Due. Topics. * 5.1 What is a Signal? * Dealing with Signals - masks, handlers

Chapter 1 Introduction

Exceptional Control Flow Part II

ECF Exists at All Levels of a System Exceptional Control Flow Part II Oct. 22, 2002 Topics! Process Hierarchy! Shells! Signals!

Lecture 24: Multitasking and Signals

UNIX System Programming. Overview. 2. Signal Types (31 in POSIX) Signal Sources. Signals. 1. Definition

Technical Document Series. POSIX Signal Handling in Java

Giving credit where credit is due

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 20

CSE410 Operating Systems Spring 2018 Project 1: Introduction to Unix/Linux Signals

Acontecimentos assíncronos (POSIX signals) Sincronização com múltiplos acontecimentos

Lecture 4 Threads. (chapter 4)

COSC243 Part 2: Operating Systems

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 19

Lecture 9: Real-Time Software Design Issues

Signals and Signal Handling - Part 2

Course Syllabus. Operating Systems, Spring 2016, Meni Adler, Danny Hendler & Amnon Meisels

Exceptions, Processes and Signals

CS631 - Advanced Programming in the UNIX Environment. Process Groups, Sessions, Signals

Chapter 9. Signals and Signal Processing

CSCI0330 Intro Computer Systems Doeppner. Project Shell 2. Due: November 8, 2017 at 11:59pm. 1 Introduction 2

Operating Systemss and Multicore Programming (1DT089)

Systems Programming/ C and UNIX

系統程式 郭大維教授 / 施吉昇教授臺灣大學資訊工程系

Chapter 4: Threads. Operating System Concepts 9 th Edition

Introduction. Interprocess communication. Terminology. Shared Memory versus Message Passing

PROCESS CONTROL BLOCK TWO-STATE MODEL (CONT D)

Altering the Control Flow

Concurrency Problems Signals & Synchronization Semaphore Mutual Exclusion Critical Section Monitors

Other Interprocess communication (Chapter 2.3.8, Tanenbaum)

Processes & Threads. (Chapter 3) CS 4410 Operating Systems. [R. Agarwal, L. Alvisi, A. Bracy, M. George, E. Sirer, R. Van Renesse]

Lecture 4. Introduction to Unix Processes. Introduction to Systems Programming: Processes and Signals

Altering the Control Flow

Chapter 5. TCP Client-Server

What is an Operating System? Signals, Processes, & Threads. Resource Sharing. Resource Abstraction ... Operating Systems 10/20/2010

Signals, Synchronization. CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han

Signals: Management and Implementation. Sanjiv K. Bhatia Univ. of Missouri St. Louis

CS 550 Operating Systems Spring Inter Process Communication

Exceptional Control Flow: Signals and Nonlocal Jumps

Operating System Structure

Exceptional Control Flow Part II Nov. 2, 2009"

Unix System Programming - Chapter 8

NETWORK PROGRAMMING TOTAL = 45

* What are the different states for a task in an OS?

Last Class. System Calls, Kernel Mode, and Process Implementation. Processes. Today. Operating Systems 9/11/2018 CSC 256/456 1

Operating Systems, laboratory exercises. List 2.

Transcription:

Preview Process Termination The waitpid() System Call The system() System Call Concept of Signals Linux Signals The signal System Call Unreliable Signals Signal() System Call The kill() and raise() System Call The alarm() System Call The pause() System Call The exit status of a child will be used for parent process termination When a child exits, the parent process will receive a SIGCHLD signal to indicate that one of its children has finished executing; the parent process will typically call the wait() system call at this point. That call will provide the parent with the child s exit status, and will cause the child to be reaped, or removed from the process table. 1 2 wait and waitpid() System Call wait and waitpid() System Call When a process terminate either normally or abnormally, the kernel sent a signal (SIGCHD) to a parent. A parent can ignore the signal or call a function (wait or waitpid) to take care the signal. pid_t wait (int *status); pid_t waitpid(pid_t pid, int *status, int option); The execution of wait() could have two possible situations. If there are at least one child processes, the caller will be blocked until one of its child processes exits. If there is no child process running, then this wait() has no effect at all. The status is the pointer where terminated process s status is saved. Returns ID if OK, -1 on error 3 4 /*wait.c demonstrate wait() system call */ #include <string.h> #define MAX_COUNT 1000 #define BUF_SIZE 100 void main(void) pid_t pid1, pid, p1; int status; int i; char buf[buf_size]; printf("*** Parent is about to fork ***\n"); if ((pid1 = fork()) < 0) printf("failed to fork process 1\n"); if (pid1 == 0) /* child's part */ p1= getpid(); for (i = 1; i <MAX_COUNT; i++) sprintf(buf,"child %d is running\n", p1); write(1, buf, strlen(buf)); sprintf(buf, "*** Parent enters waiting status...\n"); write(1, buf, strlen(buf)); pid = wait(&status); /*wait for child finish it's job */ sprintf(buf, "*** Parent detects process %d was done ***\n", pid); write(1, buf, strlen(buf)); printf("*** Parent exits ***\n"); 5 waitpid() System Call If a parent create more than one child, wait returns on termination of any of children process. waitpid() system call can be used to wait for specific process to terminate. pid_t waitpid(pid_t pid, int *status, int option); Returns ID if OK, -1 on error 6 1

/* waitpid4.c */ int i, status; pid_t childid,pid, endid; time_t when; if ((childid = fork()) == -1) /* Create a Child */ perror("fork error"); if (childid == 0) /* This is the child. */ printf("child process started at %s", ctime(&when)); if ((pid= fork())<0) perror("fork error"); exit(2); if (pid >0) for (i=0; i <5; i++) printf("the first child is running at %s",ctime(&when)); printf("the first child finish its job at %s",ctime(&when)); // second child while (1) printf("the second child is running at %s",ctime(&when)); /* This is the parent. */ printf("parent process started at %s", ctime(&when)); /* Wait for child process to terminate. */ endid = waitpid(childid, &status, WNOHANG WUNTRACED); if (endid == 0) /* child still running */ printf("parent waiting for child at %s", ctime(&when)); break; printf("now my child finish job at %s", ctime(&when)); exit (0); 10/23/2018 waitpid() System Call waitpid() System Call The differences between wait() and waitpid() The wait can block the caller(parent) until a child process terminates. The waitpid() has option that prevents it from blocking The waitpid() function doesn t wait for the child that terminate first; it has options that control which process parent wait for. The waitpid() system call provides three features that does not by the wait() Wait for one particular process Provide non blocking version of wait Provides support for job control Options 0: wait one by one until all terminated WNOHANG: will not block if the child is not available immediately WCONTINUED: if implementation support job control, WUNTRACED : if implementation support job control, 7 8 /* waitpid.c: demonstrate waitpid system call */ if ( (pid = fork()) < 0) /*create the first child */ exit (1); if (pid == 0) /* code for first child */ if ( (pid = fork()) < 0) exit (2); if (pid > 0) /* code for first child */ sleep (20); _ eles /* code for the second child */ sleep(10);/*second child terminate first */ printf("second child, parent pid = %d\n terminated", getppid()); _ if (waitpid(pid, NULL, 0)!= pid) /* wait for the first child */ printf("waitpid ERROR \n"); exit(3); printf("now parent %d terminated\n", pid); 9 /* waitpid1.c: demonstrate waitpid system call */ printf("my pid = %d \n", getpid()); if ( (pid = fork()) < 0) /*create the first child */ exit (1); if (pid == 0) /* code for first child */ printf("a Child pid = %d \n", getpid()); //create a second child by the first child if ( (pid = fork()) < 0) exit (2); if (pid > 0) printf("first child pid=%d is terminated\n", getpid()); /* parent from second fork == first child */ printf("gradchild's pid = %d, parent pid = %d\n",getpid(), getppid()); sleep(10); printf("second child terminated parent pid = %d\n",getppid()); if (waitpid(pid, NULL, 0)!= pid) /* wait for first child*/ printf("waitpid ERROR \n"); exit(3); printf ("now parent %d terminated \n",getppid()); 10 /* waitpid2.c */ int i, status; pid_t childid, endid; time_t when; if ((childid = fork()) == -1) /* Create a Child */ perror("fork error"); if (childid == 0) /* This is the child. */ printf("child process started at %s", ctime(&when)); sleep(10); /* Sleep for 10 seconds. */ /* This is the parent. */ printf("parent process started at %s", ctime(&when)); /* Wait 15 seconds for child process to terminate. */ for(i = 0; i < 15; i++) endid = waitpid(childid, &status, WNOHANG WUNTRACED); if (endid == 0) /* child still running */ printf("parent waiting for child at %s", ctime(&when)); printf("now my child finish job at %s", ctime(&when)); exit (0); 11 12 2

The system() System Call We can execute bash commands inside c program by using system() system call. The system() is implemented by calling fork(), exec, and waitpid, there are three types of return value - 1: If either the fork() or waitpid() failed. 127: if the exec failed Other: the termination status of waitpid() /* systemtest.c: demonstrate system() system call */ int status; if ( (status = system("date")) < 0) printf("system() ERROR\n"); printf ("Status = %d\n", status); /*non existed command */ if ( (status = system("nosuchcommand")) < 0) printf("system() ERROR\n"); exit(2); printf ("Status = %d\n", status); if ( (status = system("who; exit 44")) < 0) printf("system() ERROR\n"); exit(3); printf ("Status = %d\n", status); 13 14 Signals are software interrupts. Signals provide a way of handling asynchronous event. Signals are a fundamental method for interprocess communication. Each signal names begin with SIG. Linux support 31 standard signals (signal.h) and additional application defined signals. SIGHUP 1 Hangup (POSIX) SIGINT 2 Terminal interrupt (ANSI) SIGQUIT 3 Terminal quit (POSIX) SIGILL 4 Illegal instruction (ANSI) SIGTRAP 5 Trace trap (POSIX) SIGIOT 6 IOT Trap (4.2 BSD) SIGBUS 7 BUS error (4.2 BSD) SIGFPE 8 Floating point exception (ANSI) SIGKILL 9 Kill(can't be caught or ignored) (POSIX) SIGUSR1 10 User defined signal 1 (POSIX) SIGSEGV 11 Invalid memory segment access (ANSI) SIGUSR2 12 User defined signal 2 (POSIX) SIGPIPE 13 Write on a pipe with no reader, Broken pipe (POSIX) SIGALRM 14 Alarm clock (POSIX) SIGTERM 15 Termination (ANSI) 15 16 SIGSTKFLT 16 Stack fault SIGCHLD 17 Child process has stopped or exited, changed (POSIX) SIGCONT 18 Continue executing, if stopped (POSIX) SIGSTOP 19 Stop executing(can't be caught or ignored) (POSIX) SIGTSTP 20 Terminal stop signal (POSIX) SIGTTIN 21 Background process trying to read, from TTY (POSIX) SIGTTOU 22 Background process trying to write, to TTY (POSIX) SIGURG 23 Urgent condition on socket (4.2 BSD) SIGXCPU 24 CPU limit exceeded (4.2 BSD) SIGXFSZ 25 File size limit exceeded (4.2 BSD) SIGVTALRM 26 Virtual alarm clock (4.2 BSD) SIGPROF 27 Profiling alarm clock (4.2 BSD) SIGWINCH 28 Window size change (4.3 BSD, Sun) SIGIO 29 I/O now possible (4.2 BSD) SIGPWR 30 Power failure restart (System V) Conditions for generating signal The terminal-generated signals occur when users press certain terminal key (ctr-c, ctr-z, ctr-d ). Hardware exception generate signals invalid memory reference. kill system call allows a process to send a signal to a process or group of process kill command allows us to send signals to other process. Software condition can generate signal when something happed out of band data arrived over network 17 18 3

The kill() and raise() System Calls Kernel do one of three things for a signal Ignore the signal This works for most of signal except SIGKILL and SIGSTOP. Catch the signal ask the kernel to call a function of ours (signal handler) whenever the signal occurs. When a child process terminate, the SIGCHILD can catch by signal() or sigaction() system call and this signal can be used to initiate a user defined function. Let default action apply every signal has a default action, such as terminate or ignore. The kill() system call send a signal to a specific process or a group of processes. The raise() system call allows a process to send a signal to itself. int kill (pid_t pid, int signo); int raise (int signo); Return 0 if ok return -1 19 20 The kill() and raise() System Calls The kill() and raise() System Calls There are four different condition for the pid argument to kill(). pid >0: The signal send to the process with ID = pid. pid ==0: The signal send to all process whose process group ID equal to sender s group ID with sender has permission to send. pid <0: The signal send to all processes whose process group ID equal to the absolute value of pid with sender has permission to send. pid == -1:The signal send to all processes on the system with sender has permission to send. Permission to send The super-user can send a signal to any processes If real or effective ID of a sender s ID is same as receiver process, the sender send signal to them. 21 22 The alarm() System Call The alarm() System Call The alarm() system call allows to set a timer that will expire at a specified time in the future. When the timer expires, the SIGALAM signal is generated. unsigned int alarm (unsigned int seconds); There is only one of alarm clocks per a process. When we call alarm() system call and if a previously registered clock for the process has not yet expired, the remaining time will be return as a value of this function. Return 0 or number of seconds 23 24 4

The pause() System Call The pause() system call suspends the calling process until a signal is caught typedef void (*sighandler_t)(int); sighandler_t signal(int signo, sighandler_t); int pause (void); Return -1 with error Return -1 with error signo: name of signal SIG func: the const SIG_IGN - ignore the const SIG_DEF - default a function address to be called when the signal occurs 25 Function signal accept two arguments and return a pointer to a function that returns nothing. Second argument is pointer to a function that take a single integer argument and return nothing. 26 The pause() System Call /* alarm1.c: demonstrate a signal system call*/ void ding (int sig) time_t t =time((time_t *)0); printf("alarm fired at %s by signal = %d\n", asctime(localtime(&t)),sig); time_t t = time((time_t *)0); printf("set alram 5 second for a process at time %s\n", asctime(localtime(&t))); alarm(5); alarm(10); signal (SIGALRM, ding); 27 typedef void (*sighandler_t)(int); sighandler_t signal(int signo, sighandler_t); Return -1 with error signo: name of signal SIG func: the const SIG_IGN - ignore the const SIG_DEF - default a function address to be called when the signal occurs Function signal accept two arguments and return a pointer to a function that returns nothing. Second argument is pointer to a function that take a single integer argument and return nothing. 28 Most of the Linux users use the key combination ctrl+c to terminate processes in Linux. Whenever ctrl+c is pressed, a signal SIGINT is sent to the process. The default action of this signal is to terminate the process. But this signal can also be handled. The following code demonstrates this case 29 // catchsignal.c example for catching signal SIGINT #include<stdio.h> #include<signal.h> #include<unistd.h> void sig_handler(int signo) if (signo == SIGINT) sleep (1); time_t t =time((time_t *)0); printf("received SIGINT at %s\n", asctime(localtime(&t))); if (signal(sigint, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); // A long long wait for a signal. this process suspend for a signal pause(1); 30 5

// catchsignal1.c // example for catching SIGINT, SIGTSTP, SIGQUIT and User Defined Signals // SIGKILL, SIGSTOP cannot be catched #include<stdio.h> #include<signal.h> #include<unistd.h> void sig_handler(int signo) if (signo == SIGUSR1) printf("received SIGUSR1\n"); if (signo ==SIGINT) printf("received SIGINT:Cntl-C\n"); if (signo == SIGTSTP) printf("received SIGTSTP:Cntl-Z\n"); if (signo == SIGQUIT) printf("received SIGQUIT:Cntl-\\n"); if (signal(sigusr1, sig_handler) == SIG_ERR) printf("\ncan't catch SIGUSR1\n"); if (signal(sigint, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); if (signal(sigtstp, sig_handler) == SIG_ERR) printf("\ncan't catch SIGTSTP\n"); if (signal(sigquit, sig_handler) == SIG_ERR) printf("\ncan't catch SIGQUIT\n"); // catchsignal2.c // example for catching SIGINT, SIGTSTP, SIGQUIT and User Defined Signals #include<stdio.h> #include<signal.h> #include<unistd.h> void sig_handler(int signo) if (signo == SIGUSR1) printf("received SIGUSR1\n"); if (signo ==SIGINT) printf("received SIGINT:Cntl-C\n"); if (signo == SIGTSTP) printf("received SIGTSTP:Cntl-Z\n"); if (signo == SIGQUIT) printf("received SIGQUIT:Cntl-\\n"); int count =0; pid = getpid(); if (signal(sigusr1, sig_handler) == SIG_ERR) printf("\ncan't catch SIGUSR1\n"); if (signal(sigint, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); if (signal(sigtstp, sig_handler) == SIG_ERR) printf("\ncan't catch SIGTSTP\n"); if (signal(sigquit, sig_handler) == SIG_ERR) printf("\ncan't catch SIGQUIT\n"); 31 count++; if (count > 5) kill(pid, SIGKILL); 32 /* sig_talk1.c */ /* a process keep running waiting for a signal */ static void sig_usr(int); /* signal handler */ if (signal(sigusr1, sig_usr) == SIG_ERR) printf("can't catch SIGUSR1"); if (signal(sigusr2, sig_usr) == SIG_ERR) printf("can't catch SIGUSR2"); for ( ; ; ) /* can wait for signal */ /* sinal handler must have one single integer */ static void sig_usr(int signo) if (signo == SIGUSR1) printf("received SIGUSR1\n"); if (signo == SIGUSR2) printf("received SIGUSR2\n"); printf("received not SIGUSR1 or SIGUSR2\n"); 33 /*signal.c send signal to a process */ int pid =11294; int i; for (i =1; i<=20 i++) if ( i % 2 == 1) kill (pid, SIGUSR1); kill(pid, SIGUSR2); 34 /* sig_talk2.c: demonstrate a signal system call*/ static int alarm_fired = 0; void ding (int sig) alarm_fired = 1; printf("alarm application start \n"); if ((pid = fork() <0)) perror ("fork error"); exit (1); if (pid == 0) /* child process */ printf("child is about to sleep 5 second\n"); sleep(5); kill(getppid(), SIGALRM); /* parent process */ printf(" waiting for alarm from child at %s \n",asctime(localtime(&t))); signal (SIGALRM, ding); if (alarm_fired) time_t t =time((time_t *)0); printf("my child send SIGALRM at %s \n",asctime(localtime(&t))); exit (0); 35 6