#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/inch.h>#include<errno.h>#include<signal.h>#defineErrexit (msg) (Perror (msg), (Exit (exit_failure)))#defineListen_port 8888#defineBuf_size 1024Static volatilesig_atomic_t Gotsigio =0;Static voidSigiohandler (intSIG) {Puts ("I got the Sigio"); Gotsigio=1;}intMake_sock (void){ intSOCKFD; structsockaddr_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, (structsockaddr*) &clientaddr,sizeof(CLIENTADDR)) <0) {Errexit ("Bind"); } Listen (SOCKFD,5); returnsockfd;}intMainvoid){ intSOCKFD,CONNFD; structsockaddr_in clientaddr; intN; CharBuf[buf_size]; structsigaction 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, (structsockaddr*) (Null,null)) <0) {Errexit ("Accept"); } //todo.. intID; 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); intflags; 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