This is a creation in Article, where the information may have evolved or changed.
Signaling (Signal) is a way for interprocess communication in Linux, Unix-like, and other POSIX-compliant operating systems. A signal is an asynchronous notification that is sent to a process, or to a thread of the same process, telling them that an event has occurred.
When the signal is sent to a process, the operating system interrupts the normal process of the process and enters the appropriate signal handler to perform the operation, and then goes back to where it was interrupted.
If the target process previously registered a handler for a signal (signal handler), the handler is called, otherwise the default handler is called.
Send Signal
Kill system Call
Can be used to send a specific signal to the process.
Kill command
Allows the user to send a specific signal to the process.
Raise Library functions
A specific signal can be sent to the current process.
Run man kill under Linux to see the introduction and usage of this command.
The Commandkill
Sends the specified signal to the specified process or process group. If no signal is specified, the term signal is sent. The term signal would kill processes which do not catch this signal. For other processes, it is necessary the KILL (9) signal, since this signal cannot is caught.
Most modern shells has a builtin kill function, with a usage rather similar to that of the command described here. The '-a ' and '-p ' options, and the possibility to specify PIDs by command name are a local extension.
The If sig is 0 and then no signal are sent, but the error checking is still performed.
Some exceptions, such as dividing by 0 or segmentation violation, generate SIGFPE and SIGSEGV signals, which, by default, cause core dump and program to exit.
The kernel sends signals in certain situations, such as when a process writes data to a closed pipe, which generates a sigpipe signal.
Typing a specific key combination at the terminal of a process also causes the system to send a specific signal to the process:
Ctrl-c sends an INT signal (SIGINT), which usually causes the process to end
Ctrl-z Send TSTP signal (SIGTSTP); Usually causes the process to hang (suspend)
ctrl-\ Send QUIT signal (sigquit); Usually leads to process end and dump core.
CTRL-T (not all UNIX-supported) Send info signal (SIGINFO); Information that causes the operating system to display this run command
The kill-9 PID sends a sigkill signal to the process.
Processing signal
Signal handler can be set through the Signal () system call. If not set, the default handler will be called, and of course the process can also be set to ignore this signal.
There are two types of signals that cannot be intercepted and processed: Sigkill and Sigstop.
When the signal is received, the process performs the corresponding action according to the response action of the signal, the response of the signal is as follows:
- Abort process (term)
- Ignore signal (IGN)
- Abort process and save memory information (Core)
- Stop process (STOP)
- Continue running Process (Cont)
The user can modify the response action of the signal via the signal or sigaction function (that is, the "registered signal"). In addition, in multi-threading, the signal response actions of each thread are the same, and a separate response action cannot be set on a thread.
Signal type
The signal definition of a platform may be somewhat different. The signals defined in POSIX are listed below.
Linux uses 34-64 signals as a real-time system.
The Command Man 7 signal provides an official signal presentation.
List of signals defined in the posix.1-1990 standard
Signal Value Action Description
SIGHUP 1 Term Terminal control process end (terminal connection disconnected)
SIGINT 2 Term user sends Intr character (CTRL + C) trigger
Sigquit 3 Core user sends the Quit character (ctrl+/) trigger
Sigill 4 Core Illegal Instruction (program error, attempt to execute data segment, stack overflow, etc.)
SIGABRT 6 Core call abort function trigger
SIGFPE 8 Core arithmetic run error (floating-point arithmetic error, divisor is zero, etc.)
SIGKILL 9 Term Unconditional End program (cannot be captured, blocked, or ignored)
SIGSEGV one Core Invalid memory reference (attempting to access a memory space that does not belong to itself, write to read-only memory space)
Sigpipe the message pipeline is corrupted (fifo/socket communication, the pipeline is not open and writes)
SIGALRM Clock timing signal
SIGTERM term closure procedure (can be captured, blocked, or ignored)
SIGUSR1 30,10,16 Term User retention
SIGUSR2 31,12,17 Term User retention
SIGCHLD 20,17,18 Ign Child process End (received by parent process)
Sigcont 19,18,25 Cont continue execution of stopped processes (cannot be blocked)
SIGSTOP 17,19,23 Stop Stop process (cannot be caught, blocked, or ignored)
SIGTSTP 18,20,24 Stop Stop process (can be caught, blocked, or ignored)
Sigttin 21,21,26 Stop daemon triggers when reading data from the terminal
Sigttou 22,22,27 Stop daemon triggers when writing data to the terminal
List of signals in the SUSV2 and posix.1-2001 standards:
Signal Value Action Description
SIGTRAP 5 Core trap instruction trigger (e.g. breakpoint, used in debugger)
Sigbus 0,7,10 Core Illegal address (memory address alignment error)
Sigpoll term pollable event (Sys V). Synonym for SIGIO
Sigprof 27,27,29 term Performance clock signal (includes system call time and process consuming CPU time)
Sigsys 12,31,12 Core Invalid system call (SVR4)
Sigurg 16,23,21 Ign has emergency data to reach socket (4.2BSD)
SIGVTALRM 26,26,28 term Virtual clock signal (process consumes CPU time) (4.2BSD)
SIGXCPU 24,24,30 Core exceeds CPU time resource limit (4.2BSD)
Sigxfsz 25,25,31 Core exceeds file size resource limit (4.2BSD)
signal send and process in go
Sometimes we want to process signal signals in the GO program, such as gracefully closing a program after receiving a sigterm signal (see the application in the next section).
The GO signal notification mechanism can be implemented by sending os.signal to a channel.
First we create an OS. Signal channel, then use Signal. Notify register to receive the signal.
12345678910111213141516171819202122232425262728293031323334353637
Package Mainimport "FMT" import "OS" import "os/signal" import "Syscall" Func Main () {//GO signal notification works by send Ingos.SignalValues on a channel. We ll create a channel to//receive these notifications (we'll also make one to//notify us when the program can exit). SIGs: = Make (chan os. Signal, 1) Done: = Make (chan bool, 1)//signal.NotifyRegisters the given channel to//receive notifications of the specified signals. Signal. Notify (SIGs, Syscall. SIGINT, Syscall. SIGTERM)//This goroutine executes a blocking receive for//signals. When it gets one it's ll print it out//and then notify the program that it can finish. Go func () {sig: = <-sigs FMT. Println () fmt. Println (SIG) Done <-True} ()//The program would wait here until it gets the//expected signal (as indicated by the G Oroutine//above sending a value ondone) and then exit. Fmt. PRINTLN ("Awaiting signal") <-done FMT. Println ("Exiting")}
Go run Main.go executes this program, and typing CTRL-C sends a SIGINT signal. This program will print out after receiving this signal.
Go Web server if a seamless restart
Go is ideal for writing server-side network programs. One of the things that DevOps often encounters is upgrading the system or reloading the configuration file, in which case we need to restart the network program, and if the network program pauses for a longer period of time, the customer feels bad.
How to gracefully restart a Go network program. There are two main issues to solve:
Process Restart does not need to shut down the listening port
Both requests should be fully processed or timed out
@humblehack provides a way in his article graceful Restart in Golang, while Florian von Bock implements a framework endless according to this idea.
This framework is super simple to use:
1
ERR: = Endless. Listenandserve ("localhost:4242", MUX)
Just replace HTTP. Listenandserve and Http.listenandservetls.
It will listen to these signals: Syscall. Sighup,syscall. Sigusr1,syscall. Sigusr2,syscall. Sigint,syscall. SIGTERM, and Syscall. SIGTSTP.
The ideas mentioned in this article are:
through exec. Commandfork a new process that inherits the open file of the current process (input output, socket, etc.)
1234567891011121314
File: = Netlistener.file ()//This returns A Dup () path: = "/path/to/executable" args: = []string{"-graceful"}cmd: = Exec. Command (path, args ...) Cmd. Stdout = OS. Stdoutcmd.stderr = OS. Stderrcmd.extrafiles = []*os. File{file}err: = cmd. Start () if err! = Nil {log. Fatalf ("Gracefulrestart:failed to launch, error:%v", err)}
Child process initialization
The startup code of the network program
12345678910111213141516
Server: = &http. SERVER{ADDR: "0.0.0.0:8888"} var gracefulchild bool var l net. Listever var err error flag. Boolvar (&gracefulchild, "graceful", false, "Listen on FD open 3 (internal with only)") if Gracefulchild {log. Print ("main:listening to existing file descriptor 3.") F: = OS. NewFile (3, "") l, err = net. Filelistener (f)} else {log. Print ("main:listening on a new file descriptor.") L, err = net. Listen ("TCP", server. ADDR)}
Parent process stopped
1234567
If Gracefulchild {parent: = Syscall. Getppid () log. Printf ("main:killing parent pid:%v", parent) syscall. Kill (parent, Syscall. SIGTERM)}server. Serve (L)
He also provides how to handle requests that are already being processed. You can view its articles for details.
Therefore, processing a specific signal can achieve a seamless restart of the program.
Resources
Https://en.wikipedia.org/wiki/Unix_signal
http://hutaow.com/blog/2013/10/19/linux-signal/
/http/ Www.ucs.cam.ac.uk/docs/course-notes/unix-courses/Building/files/signals.pdf
https://golang.org/pkg/os/ signal/
Https://gobyexample.com/signals
http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/
https://fitstar.github.io/falcore/hot_restart.html
Https://github.com/rcrowley/goagain