Junior — Middle
What is the role and purpose of signals in the Linux operating system?
sobes.tech AI
Answer from AI
Signals in the Linux operating system are mechanisms for asynchronous notification of a process about the occurrence of certain events. They allow processes to respond to external or internal events, such as interrupts, errors, or user requests.
Role of signals:
- Notifying a process about events (e.g., termination of a child process, pressing Ctrl+C).
- Managing processes (e.g., stopping, continuing, terminating).
- Error handling (e.g., division by zero triggers SIGFPE signal).
A process can set a signal handler that executes upon receiving a signal, or use default behavior (termination, ignoring, etc.).
Example of handling SIGINT (Ctrl+C) in C:
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void handler(int signum) {
printf("Received signal %d, terminating\n", signum);
_exit(0);
}
int main() {
signal(SIGINT, handler);
while(1) {
printf("Working...\n");
sleep(1);
}
return 0;
}