Linux asyn-io for socket

來源:互聯網
上載者:User

標籤:

#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 1024static 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);}

 

Linux asyn-io for socket

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.