How to close the socket correctly by tcp programming under linux?

suppose there is a piece of code on the server side with two threads open, one to process the client connection and one to read the message sent by the client.

m_fd = socket(AF_INET, SOCK_STREAM, 0);

bind(...);
listen(...);

pid_t pid;
while (1)
{
    m_client_fd = accept(m_server_fd, (sockaddr*)&client_addr, &len);

    pid = fork();

    if (pid == 0) // 
    {
         close(m_fd); // 

         do_read_from_client(m_client_fd); // m_client_fd

         close(m_client_fd); // 
         exit(EXIT_SUCCESS);
    }
    else
    {
         close(m_client_fd); // 
    }
}

/*************************************************/

close(m_fd); // 

/****************************************************************/

how to turn off the file descriptor fd, correctly when it comes to multithreading?

Mar.10,2021

  1. instead of opening two processes, you start one process with one request
  2. where did m_server_fd come from?
  3. specify processes and threads, which are different in threads

if m_server_fd and m_fd are the same thing, but they are miswritten, then there is no problem


not correct

the server socket cannot accept requests without closing it.
client sockets can be closed in the child process, not in the parent process. If the parent process shuts down the child process, the child process will not be able to read it.

Menu