Signals and Message Queues

Total Page:16

File Type:pdf, Size:1020Kb

Signals and Message Queues Signals and Message Queues April 8, 2013 Inter-Process Communication • Why IPC? Allows for processes to work together, but remain otherwise isolated. • Segment-based IPC – Ex: memory-mapped files, shared memory • Stream-based IPC – Ex: pipes, fifos, network sockets • Message-based IPC – Ex: signals, message queues, message passing Signals are “events” • Signals communicate asynchronous events Signal Event Default Action SIGINT “Interactive Attention” (usually Ctrl+C) Process termination SIGSEGV Non-mapped Memory Access (seg. fault) Process termination SIGTERM Request for process termination (eg: Process termination system is being shut down) SIGCHLD Child process terminated, stopped, or Nothing (ignored) continued SIGSTOP* Stops process execution Stop SIGKILL* Kills process Process termination SIGALRM System alarm clock expired Process termination SIGUSR1 User-defined event Process termination SIGUSR2 User-defined event Process termination Inter-Process Communication • On Friday, we replaced the default signal handler with a custom-defined signal handler. • Problem: What if we get a signal while we are in our signal handler? Signal Mask • A signal mask is a mask that will preserve the existence of a signal, but block it from being handled until the mask is removed. INT QUIT SEGV TERM USR1 USR2 Signal Bitmap: 0 0 0 0 1 0 ... Signal Mask: 1 0 1 0 1 0 ... Every process has its own unique signal bitmap and mask! Modifying the Signal Mask Examine and change blocked signals: sigprocmask(int how, const sigset_t *set, sigset_t *oldset); Manipulate the sigset_t set: sigemptyset(sigset_t *set); sigfullset (sigset_t *set); sigaddset (sigset_t *set, int sig); sigdelset (sigset_t *set, int sig); sigismember(sigset_t *set, int sig); Signal Handlers and Signal Masks • As part of installing a custom signal handler, we also specify a custom signal mask to be applied while we handle the signal. How? • Using the easy way to handle a signal, using signal(): – The signal mask applied to our signal handler blocks only the signal that was delivered. • The proper way: int sigaction( int signum, struct sigaction *act, struct sigaction *oldact); struct sigaction { void (*sa_handler)(int); sigset_t sa_mask; ... }; A Signal’s Lifecycle Code Example void handler(int sig) { printf(“In signal handler!”); while (1) { } } int main() { signal(SIGINT, handler); while (1) { } return 0; } Some Other Common Uses of Signals • System Call: int alarm(int seconds) – Set an alarm clock for the delivery of a signal. – Usage: Log system state every X seconds to a log file. • Debugging: Many programs use a signal to print debugging information. – In Java: Pressing Ctrl+\ (SIGQUIT) on a Java process will print out the current state of every thread. • Interrupting blocking calls: Many C system calls will return if a signal is delivered to your process. – Eg: write(), sleep(), etc. Common Interview Question • If they only IPC mechanism you have are signals, how can I create a program to send a long message (eg: any string) from a server to a client? Message Queues • The POSIX solution to passing a message: message queues. – Multiple processes register to the same message queue using mq_open(). – A process sends a message with mq_send(). • Sends a string up to a system-defined length (~8 KB) – A process can receive a message by: • Calling mq_receive(), a blocking call. • Calling mq_notify(), setting up for a signal to be sent when a message is received. Message Queues • Why are message queues rarely used? .
Recommended publications
  • Practical Session 1, System Calls a Few Administrative Notes…
    Operating Systems, 142 Tas: Vadim Levit , Dan Brownstein, Ehud Barnea, Matan Drory and Yerry Sofer Practical Session 1, System Calls A few administrative notes… • Course homepage: http://www.cs.bgu.ac.il/~os142/ • Contact staff through the dedicated email: [email protected] (format the subject of your email according to the instructions listed in the course homepage) • Assignments: Extending xv6 (a pedagogical OS) Submission in pairs. Frontal checking: 1. Assume the grader may ask anything. 2. Must register to exactly one checking session. System Calls • A System Call is an interface between a user application and a service provided by the operating system (or kernel). • These can be roughly grouped into five major categories: 1. Process control (e.g. create/terminate process) 2. File Management (e.g. read, write) 3. Device Management (e.g. logically attach a device) 4. Information Maintenance (e.g. set time or date) 5. Communications (e.g. send messages) System Calls - motivation • A process is not supposed to access the kernel. It can’t access the kernel memory or functions. • This is strictly enforced (‘protected mode’) for good reasons: • Can jeopardize other processes running. • Cause physical damage to devices. • Alter system behavior. • The system call mechanism provides a safe mechanism to request specific kernel operations. System Calls - interface • Calls are usually made with C/C++ library functions: User Application C - Library Kernel System Call getpid() Load arguments, eax _NR_getpid, kernel mode (int 80) Call sys_getpid() Sys_Call_table[eax] syscall_exit return resume_userspace return User-Space Kernel-Space Remark: Invoking int 0x80 is common although newer techniques for “faster” control transfer are provided by both AMD’s and Intel’s architecture.
    [Show full text]
  • Interprocess Communication 1 Processes • Basic Concept to Build
    Interprocess Communication 1 Processes • Basic concept to build the OS, from old IBM mainframe OS to the most modern Windows • Used to express the requirements to be met by an OS – Interleave the execution of multiple processes, to maximize CPU utilization while providing good response time – Allocate resources to processes using a policy while avoiding deadlocks – Support interprocess communications and user creation of processes to help structuring applications • Background – Computer platform * Collection of hardware resources – CPU, memory, I/O modules, timers, storage devices – Computer applications * Developed to perform some task * Input, processing, output – Efficient to write applications for a given CPU * Common routines to access computer resources across platforms * CPU provides only limited support for multiprogramming; software manages sharing of CPU and other re- sources by multiple applications concurrently * Data and resources for multiple concurrent applications must be protected from other applications • Process – Abstraction of a running program – Unit of work in the system – Split into two abstractions in modern OS * Resource ownership (traditional process view) * Stream of instruction execution (thread) – Pseudoparallelism, or interleaved instructions – A process is traced by listing the sequence of instructions that execute for that process • Modeling sequential process/task – Program during execution – Program code – Current activity – Process stack * Function parameters * Return addresses * Temporary variables –
    [Show full text]
  • Operating Systems Homework Assignment 2
    Operating Systems Homework Assignment 2 Preparation For this homework assignment, you need to get familiar with a Linux system (Ubuntu, Fedora, CentOS, etc.). There are two options to run Linux on your Desktop (or Laptop) computer: 1. Run a copy of a virtual machine freely available on-line in your own PC environment using Virtual Box. Create your own Linux virtual machine (Linux as a guest operating system) in Windows. You may consider installing MS Windows as a guest OS in Linux host. OS-X can host Linux and/or Windows as guest Operating systems by installing Virtual Box. 2. Or on any hardware system that you can control, you need to install a Linux system (Fedora, CentOS Server, Ubuntu, Ubuntu Server). Tasks to Be Performed • Write the programs listed (questions from Q1 to Q6), run the program examples, and try to answer the questions. Reference for the Assignment Some useful shell commands for process control Command Descriptions & When placed at the end of a command, execute that command in the background. Interrupt and stop the currently running process program. The program remains CTRL + "Z" stopped and waiting in the background for you to resume it. Bring a command in the background to the foreground or resume an interrupted program. fg [%jobnum] If the job number is omitted, the most recently interrupted or background job is put in the foreground. Place an interrupted command into the background. bg [%jobnum] If the job number is omitted, the most recently interrupted job is put in the background. jobs List all background jobs.
    [Show full text]
  • The RISC-V Instruction Set Manual, Volume II: Privileged Architecture, Version 1.10”, Editors Andrew Waterman and Krste Asanovi´C,RISC-V Foundation, May 2017
    The RISC-V Instruction Set Manual Volume II: Privileged Architecture Privileged Architecture Version 1.10 Document Version 1.10 Warning! This draft specification may change before being accepted as standard by the RISC-V Foundation. While the editors intend future changes to this specification to be forward compatible, it remains possible that implementations made to this draft specification will not conform to the future standard. Editors: Andrew Waterman1, Krste Asanovi´c1;2 1SiFive Inc., 2CS Division, EECS Department, University of California, Berkeley [email protected], [email protected] May 7, 2017 Contributors to all versions of the spec in alphabetical order (please contact editors to suggest corrections): Krste Asanovi´c,Rimas Aviˇzienis,Jacob Bachmeyer, Allen J. Baum, Paolo Bonzini, Ruslan Bukin, Christopher Celio, David Chisnall, Anthony Coulter, Palmer Dabbelt, Monte Dal- rymple, Dennis Ferguson, Mike Frysinger, John Hauser, David Horner, Olof Johansson, Yunsup Lee, Andrew Lutomirski, Jonathan Neusch¨afer,Rishiyur Nikhil, Stefan O'Rear, Albert Ou, John Ousterhout, David Patterson, Colin Schmidt, Wesley Terpstra, Matt Thomas, Tommy Thorn, Ray VanDeWalker, Megan Wachs, Andrew Waterman, and Reinoud Zandijk. This document is released under a Creative Commons Attribution 4.0 International License. This document is a derivative of the RISC-V privileged specification version 1.9.1 released under following license: c 2010{2017 Andrew Waterman, Yunsup Lee, Rimas Aviˇzienis,David Patterson, Krste Asanovi´c.Creative Commons Attribution 4.0 International License. Please cite as: \The RISC-V Instruction Set Manual, Volume II: Privileged Architecture, Version 1.10", Editors Andrew Waterman and Krste Asanovi´c,RISC-V Foundation, May 2017. Preface This is version 1.10 of the RISC-V privileged architecture proposal.
    [Show full text]
  • Contents of Lecture 8 on UNIX History
    Contents of Lecture 8 on UNIX History Before UNIX Origin of UNIX Commerical wars and other threats Linux Game over. UNIX won. Continued work by the original UNIX team: Plan 9 and Inferno Microkernels vs Monolithic kernels and other issues. Jonas Skeppstedt ([email protected]) Lecture 8 2014 1 / 67 CTSS The Compatible Time-Sharing System was designed at MIT in the early 1960s. Supported up to 32 simultanously logged in users: proof of the time-sharing idea. Ran on IBM 7090 with 32K 36 bit words, of which the monitor used 5K. User programs were swapped in from a magnetic drum (disk). Multilevel feedback scheduling queue. Higher priorities have shorter time quantum Initial priority (quantum) reflects size of the executable file so it can be swapped in and run. CTSS was extremely successful and used as late as 1972: basis for MULTICS. Jonas Skeppstedt ([email protected]) Lecture 8 2014 2 / 67 MULTICS Multiplexed Information and Computing Ser vice designed by MIT, AT&T, and GE. AT&T and GE provided telephone and electricity ser vices as utilities. GE also produced computers, eg the GE-645 used in MULTICS development. Why not do the same with computing power? The goal was one computer for 100,000s users in Boston (on hardware equivalent to about 386 or 486). Designed as an extension to CTSS with virtual memory and sophisticated protection (more levels than UNIX user vs superuser). MULTICS was written in PL/1 and consisted of about 300,000 lines. Jonas Skeppstedt ([email protected]) Lecture 8 2014 3 / 67 End of MULTICS Lots of people were very enthusiastic about MULTICS, including the newly graduated Ken Thompson from Berkeley.
    [Show full text]
  • ECE391 Notes on Posix Threads
    ECE391 Lecture Notes: Abstractions and Interfaces in the Posix Thread and Semaphore APIs Steven S. Lumetta December 27, 2009 A number of elective courses open to you after ECE 391 will assume that you have some familiarity and experience with user-level synchronization and threading, primarily in the form of the Posix application programming interfaces (APIs). This set of notes is meant to help you bridge the gap between the synchronization abstractions and interfaces provided by the Linux kernel for use within the kernel and those provided by the Posix standard for application developers. The Posix mechanisms are designed to embrace a wider variety of approaches than those provided by the Linux kernel, but add little conceptually, and should not be difficult for you to pick up and use. These notes are then intended to help you map from the Posix API into concepts that you have learned in ECE 391 and to explain some of the engineering decisions that went into the Posix API and any other implementations that you might use in the future. Some of the material here was developed originally for ECE 498SL in the Spring 2009 semester. As with the other ECE391 notes, in order to make the notes more useful as a reference, definitions are highlighted with boldface, and italicization emphasizes pitfalls. 1 Posix: What andWhy The acronym POSIX stands for Portable Operating System Interface for uniX, and is used to refer to several standards organized and published by the Institute of Electrical and Electronics Engineers (IEEE) to provide a common basis for programmers to leverage operating system functionality.
    [Show full text]
  • Feb 27, 2019 Sleep and Wakeup
    CS 134 Operating Systems Feb 27, 2019 Sleep and Wakeup This work is a derivative of Sleep & Wakeup by MIT Open Courseware used under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license Outline • User-level thread switch homework • Sequence coordination •xv6: sleep & wakeup •lost wakeup problem •termination 2 HW 8: xv6 uthreads /* Switch from current_thread to next_thread. Make next_thread * the current_thread, and set next_thread to 0. * Use eax as a temporary register; it is caller saved. */ .globl thread_switch thread_switch: pushal /* save general registers */ movl current_thread, %eax movl %esp, (%eax) movl next_thread, %eax movl %eax, current_thread movl (%eax), %esp popal /* pop general registers */ ret /* pop return address */ 3 HW 8: xv6 uthreads void thread_schedule(void) { thread_p t; /* Find another runnable thread. */ next_thread = 0; for (t = all_thread; t < all_thread + MAX_THREAD; t++) { if (t->state == RUNNABLE && t != current_thread) { next_thread = t; break; } } if (t >= all_thread + MAX_THREAD && current_thread->state == RUNNABLE) { /* The current thread is the only runnable thread; run it. */ next_thread = current_thread; } if (next_thread == 0) { printf(2, "thread_schedule: no runnable threads\n"); exit(); } if (current_thread != next_thread) { /* switch threads? */ next_thread->state = RUNNING; thread_switch(); } else next_thread = 0; } 4 Sequence coordination • Threads need to wait for specific events or conditions: •Wait for disk read to complete •Wait for pipe reader(s) to make space
    [Show full text]
  • Reenix: Implementing a Unix-Like Operating System in Rust
    Reenix: Implementing a Unix-Like Operating System in Rust Alex Light (alexander [email protected]) Advisor: Tom Doeppner Reader: Shriram Krishnamurthi Brown University, Department of Computer Science April 2015 Abstract This paper describes the experience, problems and successes found in implementing a unix-like operating system kernel in rust. Using the basic design and much of the lowest-level support code from the Weenix operating system written for CS167/9 I was able to create a basic kernel supporting multiple kernel processes scheduled cooperatively, drivers for the basic devices and the beginnings of a virtual file system. I made note of where the rust programming language, and its safety and type systems, helped and hindered my work and made some, tentative, performance comparisons between the rust and C implementations of this kernel. I also include a short introduction to the rust programming language and the weenix project. Contents 1 Introduction 1 Introduction 1 Ever since it was first created in 1971 the UNIX operat- 1.1 The Weenix OS . .2 ing system has been a fixture of software engineering. 1.2 The Rust language . .2 One of its largest contributions to the world of OS engineering, and software engineering in general, was 2 Reenix 7 the C programming language created to write it. In 2.1 Organization . .7 the 4 decades that have passed since being released, C 2.2 Booting . .8 has changed relatively little but the state-of-the-art in 2.3 Memory & Initialization . .8 programming language design and checking, has ad- 2.4 Processes . .9 vanced tremendously.
    [Show full text]
  • Master Thesis Submitted in Partial Satisfaction of the Requirements for the Degree of Master of Engineering (M
    Master Thesis submitted in partial satisfaction of the requirements for the degree of Master of Engineering (M. Eng.) Irina Fedotova Name Surname Faculty of Electrical, Mechanical and Industrial Engineering, 2012, 4055928 Program, Matriculation, Matriculation number Implementation of a unified user- space time handling library under the Linux OS Prof. Dr.-Ing. E. Siemens 1. Supervisor Prof. Dr.-Ing. M. Enzmann 2. Supervisor 13.09.2012 Submission date Table of Contents List of Abbreviations ........................................................................................................ 2 1 Introduction .............................................................................................................. 3 2 Main system timers .................................................................................................. 5 2.1 Time-Stamp Counter overview .......................................................................... 5 2.1.1 Register definition and general capabilities .......................................................... 5 2.1.2 Identification of TSC implementation issues .......................................... 7 2.1.3 TSC performance optimization aspects ................................................. 8 2.2 High Precision Event Timer overview .................................................................... 10 2.2.1 Hardware implementation and general capabilities .............................. 11 2.2.2 Identification of HPET implementation issues ...................................... 11 2.2.3
    [Show full text]
  • The Liteos Operating System: Towards Unix-Like Abstractions for Wireless Sensor Networks
    The LiteOS Operating System: Towards Unix-like Abstractions for Wireless Sensor Networks Qing Cao, Tarek Abdelzaher John Stankovic Department of Computer Science Department of Computer Science University of Illinois at Urbana-Champaign University of Virginia {qcao2, zaher}@cs.uiuc.edu [email protected] Tian He Department of Computer Science University of Minnesota [email protected] Abstract sensor networks circle. The purpose of LiteOS is to sig- nificantly reduce such a learning curve. This philosophy is This paper presents LiteOS, a multi-threaded operating the operating system equivalent of network directions taken system that provides Unix-like abstractions for wireless sen- by companies such as Arch Rock [1] (that superimposes a sor networks. Aiming to be an easy-to-use platform, LiteOS familiar IP space on mote platforms to reduce the learning offers a number of novel features, including: (1) a hier- curve of network programming and management). archical file system and a wireless shell interface for user interaction using UNIX-like commands; (2) kernel support Our key contribution is to present a familiar, Unix-like for dynamic loading and native execution of multithreaded abstraction for wireless sensor networks by leveraging the applications; and (3) online debugging, dynamic memory, likely existing knowledge that common system program- and file system assisted communication stacks. LiteOS also mers (outside the current sensor network community) al- supports software updates through a separation between the ready have: Unix, threads, and C. By mapping sensor net- kernel and user applications, which are bridged through a works to file directories, it allows applying user-friendly suite of system calls.
    [Show full text]
  • CS 162: Operating Systems and Systems Programming Lecture 4: Threads and Concurrency
    CS 162: Operating Systems and Systems Programming Lecture 4: Threads and Concurrency Sept 10, 2019 Instructor: David E. Culler https://cs162.eecs.berkeley.edu Read: A&D 5.1-3, 5.7.1 HW 1 due 9/18 Groups and Section Pref Wed 9/10/19 cs162 Fa19 L08 Proj 1 released, Design doc1 Tues Recall: Multiplexing Processes • Snapshot of each process in its PCB • Only one thread active at a time per core… • Give out CPU to different processes • Scheduling • Policy Decision • Give out non-CPU resources • Memory/IO • Another policy decision Process Control Block 9/10/19 cs162 Fa19 L08 2 TCB, Stacks and Recall: Context Switch Register Mgmt 9/10/19 cs162 Fa19 L08 3 Recall: Lifecycle of a process / thread Scheduler dispatches proc/thread to run: existing proc context_switch to it terminated “forks” a new proc ready running exit syscall Create OS repr. of proc or abort • Descriptor • Address space interrupt, syscall, • Thread(s) sleep, blocking call • … Queue for scheduling completion waiting • OS juggles many process/threads using kernel data structures • Proc’s may create other process (fork/exec) • All starts with init process at boot Pintos: process.c 9/10/19 cs162 Fa19 L08 4 Recall: Process Management • exit – terminate a process • fork – copy the current process • exec – change the program being run by the current process • wait – wait for a process to finish • kill – send a signal (interrupt-like notification) to another process • sigaction – set handlers for signals 9/10/19 cs162 Fa19 L08 5 Recall: Process Management child fork pid = fork(); exec main () { if (pid == 0) ..
    [Show full text]
  • Understanding Linux Process States Author: Yogesh Babar Technical Reviewer: Chris Negus Editor: Allison Pranger 08/31/2012
    Understanding Linux Process States Author: Yogesh Babar Technical Reviewer: Chris Negus Editor: Allison Pranger 08/31/2012 OVERVIEW A process is an instance of a computer program that is currently being executed. Associated with a process is a variety of attributes (ownership, nice value, and SELinux context, to name a few) that extend or limit its ability to access resources on the computer. During the life of a process, it can go through different states. To get started with the various states of a process, compare a Linux process to a human being. Every human being has different stages of life. The life cycle begins with the parents giving birth to an offspring (synonymous to a process being forked by its parent process). After birth, humans start living their lives in their surroundings and start using available resources for their survival (synonymous to a process being in a Running state). At some point in the life cycle, humans need to wait for something that they must have before they can continue to the next step in their lives (this is synonymous to a process being in the Sleep state). And just as every human life must come to an end, every process must also die at some point in time. This tech brief will help you understand the different states in which a process can be. UNDERSTANDING PROCESS TYPES There are different types of processes in a Linux system. These types include user processes, daemon processes, and kernel processes. User Processes Most processes in the system are user processes. A user process is one that is initiated by a regular user account and runs in user space.
    [Show full text]