6

Envoyer des données en mode non bloquant

  1. /*
  2.  *
  3.  * Sends a string to udp echo server in non blocking mode and prints what it returns.
  4.  *
  5.  *   fcntl
  6.  *   poll
  7.  *   struct fds
  8.  */
  9.  
  10. #include <sys/types.h>
  11. #include <sys/socket.h>
  12. #include <sys/fcntl.h>
  13. #include <netinet/in.h>
  14. #include <sys/poll.h>
  15.  
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <strings.h>
  19. #include <errno.h>
  20. #if defined( LINUX )
  21. #include <string.h>
  22. #endif
  23.  
  24. #include <unistd.h>
  25.  
  26. #define TIMEOUT 2*1000      /* in msecs */
  27.  
  28. #define HOSTADDR    INADDR_LOOPBACK             /* 0x7F000001U */
  29. #define PORTNUM     10007                       /* IPPORT_ECHO */
  30.  
  31. int main( int argc, char **argv ) {
  32.     int sd = -1;
  33.     struct sockaddr_in sd_address;
  34.     int addrlen = sizeof (struct sockaddr_in);
  35.  
  36.     struct pollfd ps;
  37.  
  38.     char *msg = "HELLO";
  39.     char reply[16];
  40.  
  41.     if ( (sd = socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP )) == -1 )
  42.         goto error;
  43.  
  44. #if 1
  45.     /* non-blocking io */
  46.     if ( fcntl( sd, F_SETFL, O_NONBLOCK ) == -1 )
  47.         goto error;
  48. #endif
  49.  
  50.     sd_address.sin_family = AF_INET;
  51.     sd_address.sin_addr.s_addr = htonl( HOSTADDR );
  52.     sd_address.sin_port = htons( PORTNUM );
  53.  
  54.     if ( sendto( sd, msg, strlen( msg ) + 1, 0, (struct sockaddr *) &sd_address, addrlen ) == -1 )
  55.         goto error;
  56.  
  57. #if 1
  58.     /* block until ready to read */
  59.     ps.fd = sd;
  60.     ps.events = POLLIN;
  61.     switch ( poll( &ps, 1, TIMEOUT ) ) {
  62.     case 0:
  63.         errno = EWOULDBLOCK;
  64.     case -1:
  65.         goto error;
  66.     }
  67. #endif
  68.  
  69.     if ( recvfrom( sd, reply, sizeof (reply), 0, 0, 0 ) == -1 )
  70.         goto error;
  71.  
  72.     close( sd );
  73.  
  74.     fprintf( stdout, "%s\n", reply );
  75.  
  76.     exit( 0 );
  77.  
  78. error:
  79.  
  80.     fprintf( stderr, "%s(%i)\n", strerror( errno ), errno );
  81.     if ( sd != -1 )
  82.         close( sd );
  83.     exit( 1 );
  84. }

Commentaires

Pour ajouter un commentaire, cliquez ici.