Question

I have a loop that is always true to allow other clients to connect. The problem I am having is how do I constantly check the shared memory to see if it changes to know when it is time to shut down the server? The while loop I put in works but it will not let any other clients to connect after. The issue is that in the while(1) loop, it has to wait for another client to connect before going through the loop but I need it to always be checking the shared memory not just when another client connects.

    #include <sys/types.h>
    #include <netinet/in.h>
    #include <sys/socket.h>
    #include <errno.h>
    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <strings.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <sys/wait.h>

    struct sockaddr_in sn;
    struct sockaddr from;

    int main(int ac, char** other){
      int s, ns, sl, x = 22, pid;
      char b[256];
      key_t key=137; 
      int size=1;
      int shmflg=0;
      int id=0,ok=0;
      char shmstr[10];
      char istr[10];
      int *shmptr;

      size=size*sizeof(int);
      shmflg=IPC_CREAT | SHM_R | SHM_W;
      id=shmget(key,size,shmflg);
      sprintf(shmstr,"%d",id);
      shmptr=shmat(id,0,0);
      shmptr[0]=0;

      s=socket(AF_INET, SOCK_STREAM,0);
      if (s<0) {
        printf("server socket error\n");
         exit(0);}
      else {}

      bzero((char *)&sn, sizeof(sn));
      sn.sin_family = AF_INET;
      sn.sin_port = htons(3311);

      if (bind(s,(struct sockaddr *)&sn,sizeof(sn))==-1){
        printf("server bind error %d\n",errno);
        exit(0);}
      else {}

      listen(s,3);
   ////////////////////////////////////****************************************
      while (1){
        sl=sizeof(from);
        ns =accept(s,&from,&sl);
        if (ns <0) {
          printf("server accept error");
          exit(0);}
        else {}
        sprintf(b,"%d",ns);
        if ((pid=fork()) == 0) {
          sprintf(istr, "%d",ok);
          execlp(other[1], other[1], b, shmstr, istr, (char*) NULL);

        }
        else {
          while(shmptr[0]==0){}//allows the server to shut down but no more clients connect
            close(s);
            exit(0);
          }  
        }

       } 
    ////////////////////////////////////////////*************************
      close(s);
      return 0;
    }
Was it helpful?

Solution

If I understand you correctly, non-blocking socket is what you are looking for.

[edit:] use select

http://www.scottklement.com/rpg/socktut/nonblocking.html

Non-blocking sockets can also be used in conjunction with the select() API. In fact, if you reach a point where you actually WANT to wait for data on a socket that was previously marked as "non-blocking", you could simulate a blocking recv() just by calling select() first, followed by recv().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top