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
",id);

        fcntl(connfd,F_SETOWN,getpid());
     
        id = fcntl(connfd,F_GETOWN);
        printf("The id is:%d after change
",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);
}

 

Can we drop this masquerade
原文地址:https://www.cnblogs.com/landpack/p/4581865.html