Download presentation
Presentation is loading. Please wait.
1
Practical Session 2, Signals and Assignment 1
Operating Systems, 112 Practical Session 2, Signals and Assignment 1
2
Signals Signals are a way of sending simple messages to processes
Used to notify a process of important events Signals can be sent by other processes or by the kernel Signals can be found in Linux but not in xv6, you can add them yourself! Notice that there are many differences (e.g., no errno in xv6)
3
Reacting to Signals Signals are processed after a process returns from an interrupt (e.g. returning from a system call). On finishing a system call, before returning to application code, signals are dealt with (if there are any). On returning from a timer interrupt (interrupt sent by the hardware clock).
4
Signals-Asynchronous mode
Programs are synchronous: executed line by line Signals can be synchronous or asynchronous Synchronous: Dividing by zero Asynchronous: receiving a termination signal from a different process. It is not safe to call all functions, such as printf, from within a signal handler. A useful technique is to use a signal handler to set a flag and then check that flag from the main program and print a message if required
5
Signals-Examples SIGSEGV - Segmentation Faults
SIGFPE- Floating Point Error SIGTSTP – Causes process to suspend itself SIGCONT – Causes suspended process to resume execution. Which are synchronous?
6
Signal Table Each process has a signal table
Each signal has an entry in the table Each signal has a column whether to ignore the signal or not (SIG_IGN). Each signal has a column of what to do on receiving the signal (if not ignoring it). Action SIG_IGN Sig_Num 1 2
7
Blocking and Ignoring Blocking: The signal is received but not dealt with. It is kept in the signal table until the block is removed. Ignoring: The signal is received and discarded without any action being taken.
8
Signal Handlers Each signal has a default action SIGTERM – Terminate process. SIGFPE (floating point exception) –dump core and exit. The action can be changed by the process using the signal*/sigaction system call. It is highly recommended you refrain from using the signal call in your code. Nonetheless it is important to know it since it appears in many older programs.
9
Signal Handlers Five default options:
Exit: forces the process to exit. Core: forces the process to exit and create a core file. Stop: stops the process. Ignore: ignores the signal; no action taken. Continue: Resume execution of stopped process.
10
Signal Handlers Two signals cannot be ignored or have their associated action changed: SIGKILL SIGSTOP (not the same as SIGTSTP used for suspension) When calling execvp() all signals are set to their default action. The bit that specifies whether to ignore the signal or not is preserved. Why?
11
Scheme of signal processing
User Mode Kernel Mode Normal program flow do_signal() handle_signal() setup_frame() Signal handler system_call() sys_sigreturn() restore_sigcontext() Return code on the stack
12
Sending Signals Signals can be sent: From the keyboard
From the command line via the shell Using system calls
13
Keyboard Signals Ctrl–C – Sends a SIGINT signal . By default this causes the process to terminate Ctrl-\ - Sends a SIGABRT signal. Causes the process to terminate. Ctrl-Z – Sends a SIGTSTP signal. By default this causes the process to suspend execution.
14
Command line Signals kill -<signal><PID> – Sends the specified signal to the specified PID. A Negative PID specifies a whole process group. Kill -9 is SIGKILL which kills a process. killall can be used to send multiple signals to processes running specific commands fg - Resumes the execution of a suspended process (sends a SIGCONT).
15
System call Signals Kill(pid_t pid,int sig)
#include <unistd.h> /* standard unix functions, like getpid() */ #include <sys/types.h> /* various type definitions, like pid_t */ #include <signal.h> /* signal name macros, and the kill() prototype */ /* first, find my own process ID */ pid_t my_pid = getpid(); /* now that i got my PID, send myself the STOP signal. */ kill(my_pid, SIGSTOP);
16
Signal Priority Each pending signal is marked by a bit in a 32 bit word. Therefore there can only be one signal pending of each type. A process can’t know which signal came first. The process executes the signals starting at the lowest numbered signal. POSIX 2001 also defines a set of Real Time Signals which behave differently: Multiple instances may be queued Provide richer information Delivered in guaranteed order Use SIGRTMIN+n up to SIGRTMAX to refer to these signals (32 in Linux)
17
Manipulation of Signals
sighandler_t signal(int signum, sighandler_t handler) Installs a new signal handler for the signal with number signum. The signal handler is set to sighandler which may be a user specified function, or either SIG_IGN or SIG_DFL. If the corresponding handler is set to SIG_IGN, then the signal is ignored. If the handler is set to SIG_DFL, then the default action associated with the signal occurs.
18
Manipulation of Signals
On some systems (e.g. System V Unix), if the handler is set to a function sighandler then first the handler is reset, and next sighandler is called with argument signum. This may result in portability issues, or unwanted signal handling. One solution to this problem is demonstrated in the “ouch” signal handler function: void ouch(int sig) { printf(“OUCH! - I got signal %d\n”, sig); signal(SIGINT, ouch); } What is the problem with this solution? If the system does not block all other signals during signal handling, a new signal may come in before we reset the signal handler
19
Manipulation of Signals sigaction
int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact); A more sophisticated (and safe) way of manipulating signals. Doesn’t restore signal handler to default after calling signal. signum is the number of the signal act is a pointer to a struct containing much information including the new signal handler oldact if not null will receive the old signal handler. For more details and another example see: Example
20
Manipulation of Signals sigprocmask
int sigprocmask(int how, const sigset_t *set, sigset_t *oldset); The sigprocmask call is used to change the list of currently blocked signals. The behaviour of the call is dependent on the value of how, as follows: SIG_BLOCK The set of blocked signals is the union of the current set and the set argument. SIG_UNBLOCK The signals in set are removed from the current set of blocked signals. It is legal to attempt to unblock a signal which is not blocked. SIG_SETMASK The set of blocked signals is set to the argument set.
21
Manipulation of Signals sigprocmask
int sigprocmask(int how, const sigset_t *set, sigset_t *oldset); sigset_t is a basic data structure used to store the signals. The structure sent to a process is a sigset_t array of bits, one for each signal type: typedef struct { unsigned long sig[2]; } sigset_t;
22
Manipulation of Signals sigprocmask
Initialization of sigset_t can be done using: sigemptyset, sigaddset. An example of usage can be found at:
23
Example 1 #include <stdio.h> /* standard I/O functions */ #include <unistd.h> /* standard unix functions, like getpid() */ #include <sys/types.h> /* various type definitions, like pid_t*/ #include <signal.h> /* signal name macros, and the signal() prototype */ /* first, here is the signal handler */ void catch_int(int sig_num){ /* re-set the signal handler again to catch_int, for next time */ signal(SIGINT, catch_int); /* and print the message */ printf("Don't do that\n"); } int main(){ /* set the INT (Ctrl-C) signal handler to 'catch_int' */ /* now, lets get into an infinite loop of doing nothing. */ while (true) { pause(); } } Causes the process to halt execution until it receives a signal.
24
Example 2 int cpid[5]; //holds the pids of the children int j; //pointer to cpid int sigCatcher(){ // function to activate when a signal is caught signal(SIGINT,sigCatcher); //reset the signal catcher printf("PID %d caught one\n",getpid()); if(j>-1) kill(cpid[j],SIGINT); //send signal to next child in cpid }
25
Example 2-Continued int main() { int i; int zombie; int status; int pid; signal(SIGINT,sigCatcher); // set the signal catcher to sigCatcher …
26
Example 2-Continued for(i=0;i<5;i++){ if((pid=fork())== 0){ // create new child printf("PID %d ready\n",getpid()); j=i-1; pause(); // wait for signal exit(0); // end process (become a zombie) } else // Only father updates the cpid array. cpid[i]=pid; sleep(2); // allow children time to enter pause kill(cpid[4],SIGINT); // send signal to first child sleep(2); // wait for children to become zombies zombie = wait(&status); // collect zombies printf("%d is dead\n",zombie); exit(0);
27
Output PID ready PID ready PID ready PID ready PID ready PID caught one PID caught one PID caught one PID caught one PID caught one is dead is dead is dead is dead is dead
28
Security Issues Not all processes can send signals to all processes.
Only the kernel and super user can send signals to all processes. Normal processes can only send signals to processes owned by the same user.
29
Process ID Each process has an ID (pid).
Each process has a group ID (pgid). One process in the group is the group leader and all member’s group ID is equal to the leaders pid. A signal can be sent to a single process or to a process group.
30
Process Group ID A process group is a collection of related processes
All processes in a process group are assigned the same process-group identifier (pgid). The process-group identifier is the same as the PID of the process group's initial member. Used by the shell to control different tasks executed by it.
31
Process ID int getpid() – return the process’s PID. int getpgrp() – return the process’s PGID. setpgrp() – set this process’s PGID to be equal to his PID. setpgrp(int pid1, int pid2) – set process’s pid1 PGID to be equal to pid2’s PID.
32
Overview Assignment 1
33
Assignment 1 Getting to know xv6, system calls, user space programs and scheduling.
Divided into four parts: Get to know xv6, and brushing up your c skills Create and modify system calls Implement different scheduling algorithms Write user space programs You can start working on sections 1, 2 and 4 immediately. General scheduling algorithms will be discussed in practical session 4.
34
Assignment 1 Hello xv6 xv6 is a simplistic educational OS, it is used in universities such as MIT and Yale xv6 is a re-implementation of Unix Version 6, but offers only a partial implementation We will use QEMU, which is a generic and open source machine emulator and virtualizer to run xv6 Every thing you need is already in the labs
35
Assignment 1 Details We will use the svn source control to receive the initial xv6 version. We will modify that version There are two main files that are built by the make file: xv6.img and fs.img, one is the OS the other is the file system In the first task we will add to xv6 the ‘PATH’ environment variable. In addition we will add history of previous commands After creating scheduling algorithms we will add user space programs. Notice that they are different from regular c programs because they use xv6 libraries
36
Xv6 code
37
the shell int main(void) { static char buf[100]; int fd; // Assumes three file descriptors open. while((fd = open("console", O_RDWR)) >= 0){ if(fd >= 3){ close(fd); break; } // Read and run input commands. while(getcmd(buf, sizeof(buf)) >= 0){ if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){ // Clumsy but will have to do for now. // Chdir has no effect on the parent if run in the child. buf[strlen(buf)-1] = 0; // chop \n if(chdir(buf+3) < 0) printf(2, "cannot cd %s\n", buf+3); continue; if(fork1() == 0) runcmd(parsecmd(buf)); wait(); exit(); The xv6 shell uses the above calls to run programs on behalf of users. The main structure of the shell is simple; see main on line (7501). The main loop reads the input on the command line using getcmd. Then it calls fork, which creates another running shell program. The parent shell calls wait, while the child process runs the command. For example, if the user had typed "echo hello" at the prompt, runcmd would have been called with "echo hello" as the argument. runcmd (7406) runs the actual command. For the simple example, it would call exec on line (7426), which loads and starts the program echo, changing the program counter to the first instruction of echo. If exec succeeds then the child will be running echo and the child will not execute the next line of runcmd. Instead, it will be running instructions of echo and at some point in the future, echo will call exit, which will cause the parent to return from wait in main (7501).
38
the scheduler // Per-CPU process scheduler. // Each CPU calls scheduler() after setting itself up. // Scheduler never returns. It loops, doing: // - choose a process to run // - swtch to start running that process // - eventually that process transfers control // via swtch back to the scheduler. void scheduler(void) { struct proc *p; for(;;){ // Enable interrupts on this processor. sti(); // Loop over process table looking for process to run. acquire(&ptable.lock); for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){ if(p->state != RUNNABLE) continue; // Switch to chosen process. It is the process's job // to release ptable.lock and then reacquire it // before jumping back to us. proc = p; switchuvm(p); p->state = RUNNING; swtch(&cpu->scheduler, proc->context); switchkvm(); // Process is done running for now. // It should have changed its p->state before coming back. proc = 0; } release(&ptable.lock); Scheduler (line 2108) looks for a process with p->state set to RUNNABLE, and there’s only one it can find: initproc. It sets the per-cpu variable proc to the process it found and calls switchuvm to tell the hardware to start using the target process’s page table (line 2636). Changing page tables while executing in the kernel works because setupkvm causes all processes’ page tables to have identical mappings for kernel code and data. switchuvm also creates a new task state segment SEG_TSS that instructs the hardware to handle an interrupt by returning to kernel mode with ss and esp set to SEG_KDATA<<3 and (uint)proc->kstack+KSTACKSIZE, the top of this process’s kernel stack.
39
The Kill SYSTEM CALL /*** sysproc.c ***/ int sys_kill(void) { int pid; if(argint(0, &pid) < 0) return -1; return kill(pid); } /*** syscall.c ***/ static int (*syscalls[])(void) = { [SYS_chdir] sys_chdir, [SYS_close] sys_close, [SYS_dup] sys_dup, [SYS_exec] sys_exec, [SYS_exit] sys_exit, [SYS_fork] sys_fork, [SYS_fstat] sys_fstat, [SYS_getpid] sys_getpid, [SYS_kill] sys_kill, [SYS_link] sys_link, [SYS_mkdir] sys_mkdir, [SYS_mknod] sys_mknod, [SYS_open] sys_open, [SYS_pipe] sys_pipe, [SYS_read] sys_read, [SYS_sbrk] sys_sbrk, [SYS_sleep] sys_sleep, [SYS_unlink] sys_unlink, [SYS_wait] sys_wait, [SYS_write] sys_write, [SYS_uptime] sys_uptime, }; /*** proc.c ***/ // Kill the process with the given pid. // Process won't exit until it returns // to user space (see trap in trap.c). int kill(int pid) { struct proc *p; acquire(&ptable.lock); for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){ if(p->pid == pid){ p->killed = 1; // Wake process from sleep if necessary. if(p->state == SLEEPING) p->state = RUNNABLE; release(&ptable.lock); return 0; } return -1; The collection of system calls that a kernel provides is the interface that user programs see. The xv6 kernel provides a subset of the services and system calls that Unix kernels traditionally offer.
40
Midterm Question (Appendix)
41
Question from midterm 2004 תלמיד קיבל משימה לכתוב תכנית שמטרתה להריץ תכנית נתונה (ברשותו רק הקובץ הבינארי) prompt ע"י שימוש ב-fork ו-execvp. בנוסף נדרש התלמיד למנוע מן המשתמש "להרוג" את התכנית ע"י הקשת ctrl-c (שים לב כי התכנית prompt אינה מסתיימת לעולם). מצורף פתרון שהוצע ע"י תלמיד (my_prog.c) וכן התכנית prompt. תאר במדויק את פלט התכנית כאשר הקלט הנו: Good luck in the ^c midterm exam. האם הפתרון המוצע עונה על הגדרת התרגיל? אם תשובתך ל-ב' היא לא, כיצד היית משנה את התכנית my_prog.c (ניתן להוסיף/לשנות שורה או שתיים בקוד לכל היותר)?
42
Question from midterm 2004 my_prog.c
#include… void cntl_c_handler(int dummy){ signal(SIGINT, cntl_c_handler); } main (int argc,char **argv){ int waited; int stat; argv[0]=“prompt”; signal (SIGINT, cntl_c_handler); if (fork()==0){ //son execvp(“prompt”,argv[0]); else{ //father waited=wait(&stat); printf(“My son (%d) has terminated \n”,waited);
43
Question from midterm 2004 prompt.c (זכרי כי קוד זה אינו ניתן לשינוי ע"י התלמיד) main(int argc, char** argv){ char buf[20]; while(1){ printf(“Type something: “); gets(buf); printf(“\nYou typed: %s\n”,buf); }
44
Sample execution of code
תאר במדויק את פלט התכנית כאשר הקלט הנו: Good luck in the ^c midterm exam. Type something: Good luck You typed: Good luck Type something: in the ^c My son 139 has terminated
45
Code is incorrect האם הפתרון המוצע עונה על הגדרת התרגיל?
Execvp doesn’t save signal handles Therefore prompt.c doesn’t ignore ^c This means that the process can be terminated.
46
Code correction אם תשובתך ל-ב' היא לא, כיצד היית משנה את התכנית my_prog.c (ניתן להוסיף/לשנות שורה או שתיים בקוד לכל היותר)? Change signal (SIGINT, cntl_c_handler); in my_prog.c With signal (SIGINT, SIG_IGN); Add if (fork()==0){ execvp(“prompt”,argv[0]);
47
More Information http://www.linuxjournal.com/article/3985
man signal, sigaction… man kill… Process groups:
48
CODE examples
49
sigaction code example
#include <signal.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <unistd.h> sig_atomic_t sigusr1_count = 0; void handler (int signal_number){ ++sigusr1_count; } int main (int argc, char ** argv){ struct sigaction sa; memset (&sa, 0, sizeof (sa)); sa.sa_handler = &handler; sigaction (SIGUSR1, &sa, NULL); /* Do some lengthy stuff here. */ /* ... */ printf (“SIGUSR1 was raised %d times\n”, sigusr1_count); return 0; Back
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.