SIGURG信号 -- 带外数据的处理

时间:2023-02-06 03:57:56

使用SIGURG处理带外数据程序实例:

#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 BUFSIZE 1024

static int connfd;

/*SIGURG信号处理函数*/
void sig_urg(int urg)
{
int save_errno = errno;
char buffer[BUFSIZE];
memset(buffer, '\0', BUFSIZE);
int ret = recv(connfd, buffer, BUFSIZE-1 , MSG_OOB);/*MSG_OOB标志 接收带外数据*/
printf("接收到%d数据:%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("Args err");
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 sock = socket(PF_INET, SOCK_STREAM, 0);
assert(sock >= 0);

int ret = bind(sock, (struct sockaddr*)&address, sizeof(address));
assert(ret != -1);

struct sockaddr_in client;
socklen_t client_addrlength = sizeof(client);
connfd = accept(sock, (struct sockaddr*)&client, &client_addrlength);
if(connfd < 0)
{
printf("errno is %d\n", errno);
}
else
{
/*捕捉到SIGURG则执行sig_urg信号处理函数*/
addsig(SIGURG, sig_urg);
/*使用SIGURG信号前,必须设置socket的宿主进程或进程组,设为当前进程*/
fcntl(connfd, F_SETOWN, getpid());

char buffer[BUFSIZE];
/*普通数据入口*/
while(1)
{
memset(buffer, '\0', BUFSIZE);

ret = recv(connfd, buffer, BUFSIZE-1,0);
if(ret <= 0)
{
break;
}
printf("接收到%d数据:%s\n", ret, buffer);
}
close(connfd);
}
close(sock);

return 0;
}

《Linux高性能服务器编程》