When does OS check signals? - linux

For simplicity,let's suppose it's on a single core architecture.
OS' main responsibility is to assign CPU time to different processes.
When does it check signals?
My bet is that it checks it when switching context(hang proc A and wait B) ,but I don't have any proof..

The answer, sadly, depends on the OS. On most, if not all, OS signals are event-driven entities. For example, in the case of a hardware interrupt, the hardware sends the signal to the interrupt handler, which then does its stuff, usually upon a context-switch (like you suggested).
It depends on the OS exactly, but in the case of a signal sent from a specific program, it usually happens when you context-switch a process to be executed. Signals are then checked. In the case of kill, the kill command is "tied" to the process, and the OS' interrupt handler takes care of it.
Operating systems have interrupt handlers that deal with that kind of thing. They periodically check, but it realy depends on the OS. In the specific case of kill PID (I use this example because you used it in an above comment), it will check the next time PID is scheduled for continued execution.
Short but unsatisfying answer: it depends on the signal and on the OS.
Hope this helps!
N.S.
Sources: I've programmed operating systems before, and I've taken multiple concurrency classes.

It doesn't poll for them if that's what you mean. When someone asks the kernel to send a signal, it interrupts the program to handle it.
Segfaults are triggered by hardware interrupts. The interrupt handler asks the kernel to pass the message along. Timeouts are similar.
It's all event-driven. Although some of the events quickly and simply leave messages around to be collected later for later - mouse movements etc. What happens next is very system-dependent but it's not a signal anymore.

Related

C# When thread switching will most probably occur?

I was wondering when .Net would most probably switch from a thread to another?
I understand we can't predict when this will happen exactly, but is there any intelligence in this? For example, when a thread is executed will it try to wait for a method to returns or a loop to finish before switching?
I'm not an expert on .NET, but in general scheduling is handled by the kernel.
Either your thread's timeslice has expired (threads/processes only get a certain amount of CPU time)
Your thread has blocked for IO.
Some other obscure reason, like waiting for an IPC message, a network packet or something.
Threads can be preempted at any point along their execution path, be it in a loop or returning from a function. This in general isn't handled by the underlying VM (.NET or JVM) but is controlled by the OS.
Of course there is 'intelligence', of a sort:). The set of running threads can only change upon an interrupt, either:
An actual hardware interrupt from a peripheral device, eg. disk, NIC, KB, mouse, timer.
A software interrupt, (ie. a system call), that can change the state of thread/s. This encompasses sleep calls and calls to wait/signal on inter-thread synchro objects, as well as I/O calls that request data that is not immediately available.
If there is no interrupt, the OS cannot change the set of running threads because it is not entered. The OS does not know or care about loops, function/methods calls, (except those that make system calls as above), gotos or any other user-level flow-control mechanisms.
I read your question now, it may not be rellevant anymore, but after reading the above answers, i want to just to make sure:
Threads are managed (or as i know) by the process they belong to. There is nothing to do with the Operation System(and that's is the main reason why working with multithreads is more faster than working with multiprocess, because there are data sharing between threads and the switching between them is occuring faster than the context switch wich occure between process by the Short-Term-Scheduler).
(NOTE: There are two types of threads: USER_MODE' threads and KERNEL_MODE' threadss, and each os can have both of them or just on of them. Anyway a thread that working in a user application environment is considered as a USER_MODE' thread and managed by the process it's belong to.)
Am I Write?
Thanks!!!

When does a process handle a signal

I want to know when does a linux process handles the signal.
Assuming that the process has installed the signal handler for a signal, I wanted to know when would the process's normal execution flow be interrupted and signal handler called.
According to http://www.tldp.org/LDP/tlk/ipc/ipc.html, the process would handle the signal when it exits from a system call. This would mean that a normal instruction like a = b+c (or its equivalent machine code) would not be interrupted because of signal.
Also, there are system calls which would get interrupted (and fail with EINTR or get restarted) upon receiving a signal. This means that signal is processed even before the system call completes. This behaviour seems to b conflicting with what I have mentioned in the previous paragraph.
So, I am not clear as to when is the signal processed and in which process states would it be handled by the process. Can it be interrupted
Anytime it enters from kernel space to user space, or
Anytime it is in user space, or
Anytime the process is scheduled for execution by the scheduler
Thanks!
According to http://www.tldp.org/LDP/tlk/ipc/ipc.html, the process would handle the signal when it exits from a system call. This would mean that a normal instruction like a = b+c (or its equivalent machine code) would not be interrupted because of signal.
Well, if that were the case, a CPU-intensive process would not obey the process scheduler. The scheduler, in fact, can interrupt a process at any point of time when its time quantum has elapsed. Unless it is a FIFO real-time process.
A more correct definition: One point when a signal is delivered to the process is when the control flow leaves the kernel mode to resume executing user-mode code. That doesn't necessarily involve a system call.
A lot of the semantics of signal handling are documented (for Linux, anyway - other OSes probably have similar, but not necessarily in the same spot) in the section 7 signal manual page, which, if installed on your system, can be accessed like this:
man 7 signal
If manual pages are not installed, online copies are pretty easy to find.

How do system calls like select() or poll() work under the hood?

I understand that async I/O ops via select() and poll() do not use processor time i.e its not a busy loop but then how are these really implemented under the hood ? Is it supported in hardware somehow and is that why there is not much apparent processor cost for using these ?
It depends on what the select/poll is waiting for. Let's consider a few cases; I'm going to assume a single-core machine for simplification.
First, consider the case where the select is waiting on another process (for example, the other process might be carrying out some computation and then outputs the result through a pipeline). In this case the kernel will mark your process as waiting for input, and so it will not provide any CPU time to your process. When the other process outputs data, the kernel will wake up your process (give it time on the CPU) so that it can deal with the input. This will happen even if the other process is still running, because modern OSes use preemptive multitasking, which means that the kernel will periodically interrupt processes to give other processes a chance to use the CPU ("time-slicing").
The picture changes when the select is waiting on I/O; network data, for example, or keyboard input. In this case, while archaic hardware would have to spin the CPU waiting for input, all modern hardware can put the CPU itself into a low-power "wait" state until the hardware provides an interrupt - a specially handled event that the kernel handles. In the interrupt handler the CPU will record the incoming data and after returning from the interrupt will wake up your process to allow it to handle the data.
There is no hardware support. Well, there is... but is nothing special and it depends on what kind of file descriptor are you watching. If there is a device driver involved, the implementation depends on the driver and/or the device. For example, sockets. If you wait for some data to read, there are a sequence of events:
Some process calls poll()/select()/epoll() system call to wait for data in a socket. There is a context switch from the user mode to the kernel.
The NIC interrupts the processor when some packet arrives. The interrupt routine in the driver push the packet in the back of a queue.
There is a kernel thread that takes data from that queue and wakes up the network code inside the kernel to process that packet.
When the packet is processed, the kernel determines the socket that was expecting for it, saves the data in the socket buffer and returns the system call back to user space.
This is just a very brief description, there are a lot of details missing but I think that is enough to get the point.
Another example where no drivers are involved is a unix socket. If you wait for data from one of them, the process that waits is added to a list. When other process on the other side of the socket writes data, the kernel checks that list and the point 4 is applied again.
I hope it helps. I think that examples are the best to undertand it.

Context switch in Interrupt handlers

Why can't a context switch happen when an interrupt handler is executing ? More specifically, in the linux kernel, interrupt handlers run in the context of the process that was interrupted. Why is it not possible to do a context switch in the interrupt handler to schedule another process ?
On a multiprocessor, a context switch can certainly happen while an interrupt handler is executing. In fact, it would be difficult to prevent.
On a single-CPU machine, by definition it can only be running one thread of control at a time. It only has one register set, one ALU, etc. So if the interrupt handler is running there simply are no resources with which to execute a context switch.
Now, if you mean, can the interrupt handler actually call the context switch code and make one happen, well, I suppose on some systems that could be made to work. But for most, this wouldn't have much value and would be difficult to arrange. The CPU is running at elevated priority, and this priority cannot be lowered or synchronization between interrupt levels is lost. Critical sections in the OS are already synchronizing against interrupt execution and this would introduce complexities. Furthermore, a context switch happens by changing stacks, much like in a threaded user mode program, so it's hard to imagine how this might happen when the interrupt stack is needed for a return from the interrupt.
A couple of reasons, I guess, depending on the meaning of your question:
Q: Why would context switching during an interrupt be bad?
A: Interrupts are generally for interacting with hardware. Hardware is typically time-sensitive so the OS can't just stop dealing with it in the middle of something and come back when it feels like it.
Q: What stops a context switch from happening during an interrupt?
A: An interrupt happens in a special interrupt context, not a regular process context. Since it's not in a process, it's not subject to context switching as a normal process would be.
There's probably a better, deeper explanation to be made, but that's the extent of my own understanding of the matter.

How does a process come to know that it has received a signal

Please correct me if i am wrong. Here is my understanding about signals:
As far as i know, signal generation
and signal delivery are 2 different
things. In order to generate a signal,
the OS simply sets a bit in a bitarray
maintained in the Process Control
Block(PCB) of the process. Each bit
corresponds to a particular signal,
and when a bit is set, it means the
signal corresponding to the bit is
pending.
Delivery: Before transferring control
back to a process in user mode, the
Kernel always checks the pending
signals for this process. This check
must happen in Kernel space because
some signals can never be ignored by a
process – namely SIGSTOP and SIGKILL.
So does this mean that signals can only be delivered to a process when the kernel is scheduling that process i.e allocating it CPU ? Can a process get a signal when it is actually executing on the CPU ? If so, how is it possible i.e how the process comes to know that a signal is pending for it (since it is executing in User mode and cannot access the PCB)
Say there is multi processor machine and so there is real parallelism i.e multiple processes are executing at the same time. Process P1 is executing on cpu 1 and process P2 is executing on cpu2 and now process P2(having sufficient privileges) sends a signal to process P1. Will this signal be delivered to P1 right now or will it be delivered after P1 relinquishes the CPU for some reason and is again rescheduled at some later time by the Kernel and then this signal is delivered to process P1.
Please don't say this question is implementation dependent. If you find that the right answer is implementation defined then i am looking for answers in Linux, FreeBSD or any *nix platform for which you have knowledge of.
Thanks a lot for your help and patience :)
Regards
lali
The answer is implementation dependent :). On Mac OS X (and FreeBSD), signals are handled asynchronously - the kernel finds a thread which is not blocking the signal, and sets an Asynchronous System Trap flag on that thread. The next time the kernel schedules that thread, it handles the trap (quitting the process, ignoring the trap, or invoking the signal-handler in user space as appropriate) rather than arranging the usual continuation of the thread in user-space.
On Solaris, the implementation is somewhat similar, although it also offers synchronous signals based on hardware traps - synchronous signals are delivered to the thread that raised the trap, while asynchronous signals work in the way described above.
Linux does something similar to Solaris (I'm not sure how the conclusion in that reference follows from the discussion, but it's the discussion that is useful).
Posix.4 also defines real-time signals, but I haven't worked with those.
The short answer is - yes, process get knowledge of a signal only on the next scheduled CPU timeslice.
How to know the process has received a signal - it may call sigprocmask(2).
Process P1 is executing on cpu 1 and process P2 is executing on cpu2 and now process P2(having sufficient privileges) sends a signal to process P1. Will this signal be delivered to P1 right now or will it be delivered after P1 relinquishes the CPU for some reason and is again rescheduled at some later time by the Kernel and then this signal is delivered to process P1.
As far as i know on last linux kernels execution of P1 may be paused when P2 emit signal and signal will be delivered immediately. May be this true only for real-time signals
If I remember correctly, the interrupt arrival bit is checked during the last T state of an 8085 instruction. So there has to be a way to either generate a real interrupt on signal arrival, or there has to be a (constant?)code slice before the signal bit is checked.
Unfortunately, it appears that the only way to answer some kernel behaviour related questions is to go through the source code, because they are so "implementation dependent". Programming the computer really is nothing short of harassment - what a profession to choose!
Just try to be perfect, and hope this website helps.

Resources