Linux asyn-io for socket

时间:2021-07-07 13:38:17
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <signal.h> #define errExit(msg) (perror(msg),(exit(EXIT_FAILURE)))
#define LISTEN_PORT 8888
#define BUF_SIZE 1024 static volatile sig_atomic_t gotSigio = ; static void sigioHandler(int sig)
{
puts("I got the sigio");
gotSigio = ;
} int make_sock(void)
{
int sockfd;
struct sockaddr_in clientaddr;
memset(&clientaddr,SOCK_STREAM,sizeof(clientaddr));
clientaddr.sin_family = AF_INET;
clientaddr.sin_port = htons(LISTEN_PORT);
clientaddr.sin_addr.s_addr = htonl(INADDR_ANY); if((sockfd=socket(AF_INET,SOCK_STREAM,)) < )
{
errExit("socket");
} if(bind(sockfd,(struct sockaddr*)&clientaddr,sizeof(clientaddr)) < )
{
errExit("bind");
} listen(sockfd,);
return sockfd;
}
int main(void)
{
int sockfd,connfd;
struct sockaddr_in clientaddr;
int n;
char buf[BUF_SIZE]; struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sa.sa_handler = sigioHandler;
if(sigaction(SIGIO,&sa,NULL) == -)
{
errExit("sigaction");
} sockfd= make_sock(); while(){
if((connfd= accept(sockfd,(struct sockaddr*)NULL,NULL)) < )
{
errExit("accept");
}
//todo ..
int id ;
id = fcntl(connfd,F_GETOWN);
printf("The id is:%d before change\n",id); fcntl(connfd,F_SETOWN,getpid()); id = fcntl(connfd,F_GETOWN);
printf("The id is:%d after change\n",id); int flags;
flags = fcntl(connfd,F_GETFL);
// if(fcntl(connfd,F_SETFL,flags|O_ASYNC|O_NONBLOCK)==-1){
// errExit("fcntl(F_SETFL)");
// }
//the old linux version support FASYNC instean of O_ASYNC
if(fcntl(connfd,F_SETFL,flags|FASYNC|O_NONBLOCK)==-){
errExit("fcntl(F_SETFL)");
}
//while(1); }
close(sockfd);
}

Linux asyn-io for socket