Example: Worker jobs for multiple accept()

This example shows how multiple accept() APIs receive the worker jobs and call the accept() server.

Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.
/**************************************************************************/
/* Worker job uses multiple accept() to handle incoming client connections*/
/**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>

main (int argc, char *argv[])
{
   int    rc, len;
   int    listen_sd, accept_sd;
   char   buffer[80];

   /*************************************************/
   /* The listen socket descriptor is passed to     */
   /* this worker job as a command line parameter   */
   /*************************************************/
   listen_sd = 0;

   /*************************************************/
   /* Wait for an incoming connection               */
   /*************************************************/
   printf("Waiting on accept()\n");
   accept_sd = accept(listen_sd, NULL, NULL);
   if (accept_sd < 0)
   {
      perror("accept() failed");
      close(listen_sd);
      exit(-1);
   }
   printf("Accept completed successfully\n");

   /*************************************************/
   /* Receive a message from the client             */
   /*************************************************/
   printf("Wait for client to send us a message\n");
   rc = recv(accept_sd, buffer, sizeof(buffer), 0);
   if (rc <= 0)
   {
      perror("recv() failed");
      close(listen_sd);
      close(accept_sd);
      exit(-1);
   }
   printf("<%s>\n", buffer);

   /*************************************************/
   /* Echo the data back to the client              */
   /*************************************************/
   printf("Echo it back\n");
   len = rc;
   rc = send(accept_sd, buffer, len, 0);
   if (rc <= 0)
   {
      perror("send() failed");
      close(listen_sd);
      close(accept_sd);
      exit(-1);
   }

   /*************************************************/
   /* Close down the descriptors                    */
   /*************************************************/
   close(listen_sd);
   close(accept_sd);
}