Linux asyn-io for socket

#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 = 0;

static void sigioHandler(int sig)
{
    puts("I got the sigio");
    gotSigio = 1;
}

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,0)) < 0)
    {   
        errExit("socket");
    }   

    if(bind(sockfd,(struct sockaddr*)&clientaddr,sizeof(clientaddr)) < 0)
    {   
        errExit("bind");
    }   

    listen(sockfd,5);
    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) == -1) 
    {   
        errExit("sigaction");
    }   
    
    sockfd= make_sock();

    while(1){
        if((connfd= accept(sockfd,(struct sockaddr*)NULL,NULL)) < 0)
        {
            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)==-1){
            errExit("fcntl(F_SETFL)");
        }
        //while(1);

     
    }   
    close(sockfd);
}

 技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。