标签:信号驱动式io
信号驱动式I/O的本质就是:进程预先告知内核当某个描述符发生事件时,内核会向该进程发送SIGIO信号通知进程,进程可在信号处理函数中进行处理net.h
#ifndef MY_NET_H #define MY_NET_H #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <stdlib.h> #include <arpa/inet.h> #include <unistd.h> #include <time.h> #include <string.h> #include <sys/select.h> #include <sys/time.h> #include <errno.h> #include <signal.h> #include <iostream> #include <sys/stat.h> #include <fcntl.h> #include <net/if.h> #include <net/if_arp.h> #include <sys/ioctl.h> #include <sys/ioctl.h> using namespace std; char recvBuf[1025]; int listenfd; static void sigio_handler(int signo) { if (signo != SIGIO) return; int ret; while (1) { ret = recvfrom(listenfd, recvBuf, sizeof(recvBuf), 0, NULL, NULL); if (ret < 0) { if (errno == EWOULDBLOCK) break; perror("recvfrom error"); exit(-1); } cout << recvBuf << endl; } } void init(int skfd) { int ret; //1.建立SIGIO信号的处理函数 signal(SIGIO, sigio_handler); //2.设置该套接字的属主 ret = fcntl(skfd, F_SETOWN, getpid()); if (ret < 0) { perror("fcntl error"); exit(-1); } //3.开启该套接字的信号驱动式I/O int on = 1; ret = ioctl(skfd, FIOASYNC, &on); if (ret < 0) { perror("ioctl error"); exit(-1); } } int prepare() { int skfd = socket(AF_INET, SOCK_DGRAM, 0); if (skfd < 0) return -1; struct sockaddr_in saddr; bzero(&saddr, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(9999); saddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(skfd, (struct sockaddr*)&saddr, sizeof(saddr)) < 0) return -1; return skfd; } #endif
客户:
#include "net.h" int main() { int skfd; skfd = socket(AF_INET, SOCK_DGRAM, 0); if (skfd < 0) { perror("socket error"); exit(-1); } int ret; time_t tm; struct sockaddr_in desAddr; bzero(&desAddr, sizeof(desAddr)); desAddr.sin_family = AF_INET; desAddr.sin_port = htons(9999); desAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); while (1) { time(&tm); ret = sendto(skfd, ctime(&tm), strlen(ctime(&tm)), 0, (struct sockaddr*)&desAddr, sizeof(desAddr)); if (ret < 0) { perror(""); exit(-1); } sleep(1); } return 0; }
#include "net.h" int main() { listenfd = prepare(); if (listenfd < 0) { perror("prepare error"); exit(-1); } init(listenfd); while(1); return 0; }
标签:信号驱动式io
原文地址:http://blog.csdn.net/aspnet_lyc/article/details/38048251