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.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b35be5-40546.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b35be5-40546.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?