Handling multiple Connection

Hi Guys !

can you explain the following code because i want to handle multiple connection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
while(1){ 			
       newsockfd = accept(m_sockfd, (struct sockaddr*) &cli_addr, &clilen);
       pid = fork();     
       if(pid == 0){ // child
          close(m_sockfd);
          p_GameRules->start(newsockfd);		
          exit(0);
       }
      else if(pid == -1010){
           close(m_sockfd);
           p_GameRules = new GameRules();
           p_GameRules->start(newsockfd);		
           exit(0);
           }else{
                close(newsockfd);
           }
      
}
      return 1;
}


1. newsockfd what is this variable for?
2. if(pid == 0)what this means?
3. if(pid == -1010) and what -1010 means here?

Thanks in advance
Kind Regards,

Ewa
Last edited on
You should check out the man pages for these functions.

When accept() returns successfully, it returns a handle to the accepted connection.

When fork() returns 0, then the process is the newly-created child; otherwise, if fork() returns > 0, the process is the parent and pid is the process id of the newly-created process. The fork() function will return -1 if there is an error and will also set errno.

I don't have any idea why pid would equal -1010. I would change that to be:

1
2
3

    else if( pid < 0 )

Hi Kooth... Thanks for your time and help it was very informative

but can i ask you why we are closing the following things

1. close(m_sockfd);
2. close(newsockfd);

3. and what is difference between child process and parent process and why we handle them because if i remove pid ==<0 it doesn't make a difference in my program? only effected by pid == 0

4. And why there is no create(), connect(), read(), write() methods for client

Regards,

Ewa
Did you find the man pages for fork() and accept()? You really need to study these concepts before trying to use them.

Let me answer #3 first. The fork() function returns an exact copy of the process that you are running (a programmer could also create a new thread by using different calls.) The fork() function is designed such that the return code is zero for the new child process, and > 0 for the parent (unless there is an error, in which case -1 is returned to the parent process and errno is set for the appropriate reason.)

When the fork() function is successful, both the parent and the child process have copies of lots of the same items; therefore, the appropriate sockets need to be closed.

I don't know why there are no create(), connect(), read(), write() methods, but there should be, depending on whether the code is a client or a server.

accept() is where the server listens for a client connection. It blocks until a client connects. When a client establishes a new connection to the server, accept() returns a new socket representing the server's network endpoint for that connection.
Topic archived. No new replies allowed.