⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sigio.c

📁 Linux网络编程教程适合初学者入门学习
💻 C
字号:
/*sigio.c*/

#include	<sys/types.h>

#include	<sys/socket.h>

#include	<netinet/in.h>

#include	<signal.h>

#include	<unistd.h>



int	fdqueue[20];

int	qsize = 0;

int	qtail = 0;

int	lfd;

void	signal_handle();

int

main()

{

	struct sockaddr_in	addr;

	struct signaction	act;

	sigset_t		sus, nes, ols;

	fd_set			wds;

	int			maxfd = 0;

	int 			i;

	lfd = socket(AF_INET, SOCK_STREAM, 0);

	if (lfd < 0) {

		printf("socket error: %s\n", strerror(errno));

		exit(1);

	}

	i = 1;

	setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));

	bzero(&addr, sizeof(addr));

	addr.sin_family = AF_INET;

	addr.sin_port = htons(8080);

	addr.sin_addr.s_addr = htonl(INADDR_ANY);

	if (bind(lfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {

		printf("bind error: %s\n", strerror(errno));

		exit(1);

	}

	act.sa_handler = sigio_handler;

	act.sa_mask = 0;

	act.sa_flags = 0;

	sigaction(SIGIO, &act, NULL);

	fcntl(lfd, F_SETOWN, getpid());

	i = 1;

	ioctl(lfd, FIOASYNC, &i);

	for (i=0; i<20; i++)

		cfd_queue[i] = -1;

	listen(lfd, 5);

	FD_ZERO(&wds);

	sigemptyset(&sus);

	sigemptyset(&ols);

	sigemptyset(&nes);

	sigaddset(&nes, SIGIO);

	sigprocmask(SIG_BLOCK, &nes, &ols);

	for ( ; ; ) {

		for ( ; qsize == 0; )

			sigsuspend(&sus);

		sigprocmask(SIG_SETMASK, &ols, NULL);

		for (i=0; i<20; i++) {

			if (cfd_queue[i] != -1) {

				FD_SET(fdqueue[i], &wds);

			maxfd = maxfd > fdqueue[i]? maxfd:cfd_queue[i];

			}

		}

		select(maxfd+1, NULL, &wds, NULL, NULL);

		for (i=0; i<20; i++) {

			if (FD_ISSET(fdqueue[i], &wds)) {

				write(fdqueue[i], "OK!", 3);

				close(fdqueue[i]);

				sigprocmask(SIG_BLOCK, &nes, &ols);

				fdqueue[i] = -1;

				qsize--;

			}

		}

	}

}

void

signal_handle(int sig)

{

	int	err;

	int	i;

	i = sizeof(err);

	getsockopt(lfd, SOL_SOCKET, SO_ERROR, &err, &i);

	if (err) {

		printf("socket pending error: %s\n", seterror(err));

		return;

	}

	if (qsize == 20)

		return;

	for ( ; fdqueue[qtail] >= 0; )

		qtail = ++qtail % 20;

	fdqueue[qtail] = accept(lfd, NULL, NULL);

	if (fdqueue[qtail] < 0) {

		printf("accept error: %s\n", strerror(errno));

		return;

	}

	qsize++;

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -