第10章 信號(hào)
信號(hào)是由用戶、系統(tǒng)或者進(jìn)程發(fā)送給目標(biāo)進(jìn)程的信息,以通知目標(biāo)進(jìn)程某個(gè)狀態(tài)的改變或系統(tǒng)異常。
10.1 Linux信號(hào)概述
:::tips
int kill(pid_t pid, int sig);
:::
kill函數(shù):一個(gè)進(jìn)程給其他進(jìn)程發(fā)送信號(hào)的API。
sig一般大于0,如果設(shè)為0則表示不發(fā)送信號(hào),可以用來(lái)檢測(cè)進(jìn)程或進(jìn)程組是否存在。由于進(jìn)程PID的回繞(當(dāng)進(jìn)程被啟動(dòng)的時(shí)候,系統(tǒng)將按照順序選擇下一個(gè)沒(méi)有被使用的數(shù)字作為它的PID(2~32768),當(dāng)數(shù)字已經(jīng)回繞一圈的時(shí)候,新的PID重新從2開始),可能導(dǎo)致被檢測(cè)的PID不是我們期望的;另一方面,這種檢測(cè)方法不是原子操作。
:::tips
typedef void (*__sighandler_t) (int);
:::
信號(hào)處理函數(shù)是可重入的,避免引發(fā)競(jìng)態(tài)條件。
如果程序在執(zhí)行處于阻塞狀態(tài)的系統(tǒng)調(diào)用時(shí)接收到信號(hào),并且為該信號(hào)設(shè)置了信號(hào)處理函數(shù),則默認(rèn)情況下系統(tǒng)調(diào)用將被中斷,并且errno被設(shè)置為EINTR。
10.2 信號(hào)函數(shù)
:::tips
_sighandler_t signal(int sig, _sighandler_t _handler);
:::
signal函數(shù):為一個(gè)信號(hào)設(shè)置處理函數(shù)。
:::tips
int sigaction(int sig, const struct sigaction* act, struct sigaction* oact);
:::
sigaction函數(shù):設(shè)置信號(hào)處理函數(shù)的更健壯的接口??梢詾樾盘?hào)設(shè)置標(biāo)志來(lái)自動(dòng)重啟被該信號(hào)中斷的系統(tǒng)調(diào)用。
信號(hào)掩碼:指定哪些信號(hào)不能發(fā)送給本進(jìn)程。
10.3 信號(hào)集
sigset_t實(shí)際上是一個(gè)長(zhǎng)整型數(shù)組,數(shù)組的每個(gè)元索的每個(gè)位表示一個(gè)信號(hào)。與文件描述符集fd_set類似。
:::tips
int sigprocmask(Int _how, _const sigset_t * _set, sigset_t* _oset);
:::
sigprocmask函數(shù):設(shè)置或查看進(jìn)程的信號(hào)掩碼。
:::tips
int sigpending(sigset_t* set);
:::
sigpending函數(shù):信號(hào)掩碼使得被屏蔽的信號(hào)不能被進(jìn)程接收,此時(shí)該信號(hào)被掛起,通過(guò)sigpending函數(shù)獲得被掛起的信號(hào)集。此時(shí)通過(guò)sigprocmask函數(shù)可以使能被掛起的信號(hào)。
10.4 統(tǒng)一事件源
信號(hào)是一種異步事件:信號(hào)處理函數(shù)和程序的主循環(huán)是兩條不同的執(zhí)行路線。
為了盡快執(zhí)行信號(hào)處理函數(shù),可以把信號(hào)的主要處理邏輯放到程序的主循環(huán)中。信號(hào)處理函數(shù)往管道的寫端寫入信號(hào)值,主循環(huán)則從管道的讀端讀出該信號(hào)值。使用I/O復(fù)用來(lái)監(jiān)聽,信號(hào)事件就能和其他I/O事件一樣被處理,即統(tǒng)一事件源。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-736365.html
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <pthread.h>
#define MAX_EVENT_NUMBER 1024
static int pipefd[2];
int setnonblocking(int fd)
{
int old_option = fcntl(fd, F_GETFL);
int new_option = old_option | O_NONBLOCK;
fcntl(fd, F_SETFL, new_option);
return old_option;
}
void addfd(int epollfd, int fd)
{
epoll_event event;
event.data.fd = fd;
event.events = EPOLLIN | EPOLLET;
epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event);
setnonblocking(fd);
}
/* 信號(hào)處理函數(shù) */
void sig_handler(int sig)
{
/* 保留原來(lái)的errno, 在函數(shù)最后恢復(fù), 以保證函數(shù)的可重入性 */
int save_errno = errno;
int msg = sig;
send(pipefd[1], (char *)&msg, 1, 0); /* 將信號(hào)寫入管道,以通知主循環(huán) */
errno = save_errno;
}
/* 設(shè)置信號(hào)的處理函數(shù) */
void addsig(int sig)
{
struct sigaction sa;
memset(&sa, '\0', sizeof(sa));
sa.sa_handler = sig_handler;
sa.sa_flags |= SA_RESTART;
sigfillset(&sa.sa_mask);
assert(sigaction(sig, &sa, NULL) != -1);
}
int main(int argc, char *argv[])
{
if (argc <= 2)
{
printf("usage: %s ip_address port_number\n", basename(argv[0]));
return 1;
}
const char *ip = argv[1];
int port = atoi(argv[2]);
int ret = 0;
struct sockaddr_in address;
bzero(&address, sizeof(address));
address.sin_family = AF_INET;
inet_pton(AF_INET, ip, &address.sin_addr);
address.sin_port = htons(port);
int listenfd = socket(PF_INET, SOCK_STREAM, 0);
assert(listenfd > 0);
ret = bind(listenfd, (struct sockaddr *)&address, sizeof(address));
assert(ret != -1);
ret = listen(listenfd, 5);
assert(ret != -1);
epoll_event events[MAX_EVENT_NUMBER];
int epollfd = epoll_create(5);
assert(epollfd != -1);
addfd(epollfd, listenfd);
/* 使用socketpair創(chuàng)建管道,注冊(cè)pipefd[0]上的可讀事件 */
ret = socketpair(PF_UNIX, SOCK_STREAM, 0, pipefd);
assert(ret != -1);
setnonblocking(pipefd[1]);
addfd(epollfd, pipefd[0]);
/* 設(shè)置一些信號(hào)的處理函數(shù) */
addsig(SIGHUP);
addsig(SIGCHLD);
addsig(SIGTERM);
addsig(SIGINT);
bool stop_server = false;
while (!stop_server)
{
int number = epoll_wait(epollfd, events, MAX_EVENT_NUMBER, -1);
if ((number < 0) && (errno != EINTR))
{
printf("epoll failure\n");
break;
}
for (int i = 0; i < number; ++i)
{
int sockfd = events[i].data.fd;
/* 如果就緒的文件描述符是listenfd, 則處理新的連接 */
if (sockfd == listenfd)
{
struct sockaddr_in client_address;
socklen_t client_addrlength = sizeof(client_address);
int sockfd = accept(listenfd, (struct sockaddr *)&client_address,
&client_addrlength);
addfd(epollfd, sockfd);
}
/* 如果就緒的文件描述符是pipefd[0], 則處理信號(hào) */
else if ((sockfd == pipefd[0]) && (events[i].events & EPOLLIN))
{
char signals[1024];
ret = recv(pipefd[0], signals, sizeof(signals), 0);
if (ret == -1)
{
continue;
}
else if (ret == 0)
{
continue;
}
else
{
/* 因?yàn)槊總€(gè)信號(hào)值占1字節(jié),所以按字節(jié)來(lái)逐個(gè)接收信號(hào),我們以SIGTREM
* 為例,來(lái)說(shuō)明如何安全地終止服務(wù)器主循環(huán) */
for (int i = 0; i < ret; ++i)
{
switch(signals[i])
{
case SIGCHLD:
case SIGHUP:
{
continue;
}
case SIGTERM:
case SIGINT:
{
stop_server = true;
}
}
}
}
}
else
{
}
}
}
printf("close fds\n");
close(listenfd);
close(pipefd[1]);
close(pipefd[0]);
return 0;
}
10.5 網(wǎng)絡(luò)編程相關(guān)信號(hào)
SIGHUP:當(dāng)掛起進(jìn)程的控制終端時(shí),SIGHUP信號(hào)將被觸發(fā)。對(duì)于沒(méi)有控制終端的網(wǎng)絡(luò)后臺(tái)程序而言,它們通常利用SIGHUP信號(hào)來(lái)強(qiáng)制服務(wù)器重讀配置文件,例如xinetd超級(jí)服務(wù)程序。
xinetd處理SIGHUP的流程:
1)程序接收到SIGHUP信號(hào)時(shí),信號(hào)處理函數(shù)便用管道通知主程序該信號(hào)的到來(lái)。信號(hào)處理函數(shù)往管道的寫端寫入SIGHUP信號(hào),而主程序使用poll檢測(cè)到管道的讀端上有可讀事件,就將管道上的數(shù)據(jù)讀入;
2)xinetd重新讀取一個(gè)子配置文件;3或4;
3)xinetd給子進(jìn)程發(fā)送SIGTERM信號(hào)來(lái)終止該子進(jìn)程,并調(diào)用waitpid來(lái)等待該子進(jìn)程結(jié)束;(停止echo服務(wù))
4)xinetd啟動(dòng)telnet服務(wù)的過(guò)程:創(chuàng)建一個(gè)流服務(wù) socket 并將其綁定到端口上,然后監(jiān)聽該端口;(開啟telnet服務(wù))
SIGPIPE:往一個(gè)讀端關(guān)閉的管道或socket連接中寫數(shù)據(jù)將引發(fā)SIGPIPE信號(hào),程序接收到后默認(rèn)結(jié)束進(jìn)程。以poll為例檢測(cè)是否關(guān)閉:當(dāng)管道的讀端關(guān)閉時(shí),寫端文件描述符上的POLLHUP事件將被觸發(fā);當(dāng)socket連接被對(duì)方關(guān)閉時(shí),socket的POLLRDHUP事件將被觸發(fā)。
SIGURG:內(nèi)核通知應(yīng)用程序帶外數(shù)據(jù)到達(dá)。另一種方法是I/O復(fù)用技術(shù),select等系統(tǒng)調(diào)用在接收到帶外數(shù)據(jù)時(shí)將返回,并向應(yīng)用程序報(bào)告socket上的異常事件。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-736365.html
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <fcntl.h>
#define BUF_SIZE 1024
static int connfd;
/* SIGURG信號(hào)的處理函數(shù) */
void sig_urg(int sig)
{
int save_errno = errno;
char buffer[BUF_SIZE];
memset(buffer, '\0', BUF_SIZE);
int ret = recv(connfd, buffer, BUF_SIZE - 1, MSG_OOB); /* 接收帶外數(shù)據(jù) */
printf("got %d bytes os oob data '%s'\n", ret, buffer);
errno = save_errno;
}
void addsig(int sig, void (*sig_handler)(int))
{
struct sigaction sa;
memset(&sa, '\0', sizeof(sa));
sa.sa_handler = sig_handler;
sa.sa_flags |= SA_RESTART;
sigfillset(&sa.sa_mask);
assert(sigaction(sig, &sa, NULL) != -1);
}
int main(int argc, char *argv[])
{
if (argc <= 2)
{
printf("usage: %s ip_address port_number \n", basename(argv[0]));
return 1;
}
const char *ip = argv[1];
int port = atoi(argv[2]);
struct sockaddr_in address;
bzero(&address, sizeof(address));
address.sin_family = AF_INET;
inet_pton(AF_INET, ip, &address.sin_addr);
address.sin_port = htons(port);
int sockfd = socket(PF_INET, SOCK_STREAM, 0);
assert(sockfd > 0);
int ret = bind(sockfd, (struct sockaddr *)&address, sizeof(address));
assert(ret != -1);
ret = listen(sockfd, 5);
assert(ret != -1);
struct sockaddr_in client;
socklen_t client_addrlength = sizeof(client);
connfd = accept(sockfd, (struct sockaddr *)&client, &client_addrlength);
if (connfd < 0)
{
printf("errno is : %d\n", errno);
}
else
{
addsig(SIGURG, sig_urg);
/* 使用SIGURG信號(hào)之前,我們必須設(shè)置socket的宿主進(jìn)程或進(jìn)程組 */
fcntl(connfd, F_SETOWN, getpid());
char buffer[BUF_SIZE];
while (1)
{
/* 循環(huán)接收普通數(shù)據(jù) */
memset(buffer, '\0', BUF_SIZE);
ret = recv(connfd, buffer, BUF_SIZE - 1, 0);
if (ret <= 0)
{
break;
}
printf("get %d bytes of normal data '%s'\n", ret, buffer);
}
close(connfd);
}
close(sockfd);
return 0;
}
到了這里,關(guān)于Linux高性能服務(wù)器編程——ch10筆記的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!