Today, when I look at the my_server example of Linux C programming, I hit this code and ask questions about the close call to its parent-child process closing the socket.
The three close sockets in the callout, think of the communication end of the child process shut down their own communication socket:conn_fd can understand, but will sock_fd, the server's listening socket is also closed do not know how to go on. And the parent Process execution Close (CONN_FD) closes the communication socket for the child process, so that the child process cannot communicate with the client Soket soon? However, the program runs normally. Re-check Data discovery is the copy and close function of the child process resources, and the file descriptor is not understood in place
First, the socket is a special kind of data transfer Io, also a file descriptor
while(1) {conn_fd= Accept (SOCK_FD, (structSOCKADDR *) &cli_addr, &Cli_len); if(Conn_fd <0) {My_err ("Accept", __line__); } printf ("accept a new client, ip:%s\n", Inet_ntoa (CLI_ADDR.SIN_ADDR)); if(PID = fork ()) = =0) { while(1) { if(ret = recv (CONN_FD, Recv_buf,sizeof(RECV_BUF),0)) <0) {perror ("recv"); Exit (1); } Recv_buf[ret-1] =' /'; if(Flag_recv = =USERNAME) {Name_num=Find_name (RECV_BUF); Switch(name_num) { Case-1: Send_data (CONN_FD,"n\n"); Break; Case-2: Exit (1); Break; default: Send_data (CONN_FD,"y\n"); Flag_recv=PASSWORD; Break; } } Else if(Flag_recv = =PASSWORD) { if(strcmp (Users[name_num].password, recv_buf) = =0) {send_data (CONN_FD,"y\n"); Send_data (CONN_FD,"Welcome login My TCP server\n"); printf ("%s login\n", Users[name_num].username); Flag_recv=MESSAGE; } Else{send_data (CONN_FD,"n\n"); } } Else if(Flag_recv = =MESSAGE) { if(strcmp ("quit", recv_buf) = =0) { Break; } printf ("Message from%s:%s\n", Users[name_num].username, recv_buf); }} close (SOCK_FD); Close (CONN_FD); printf ("Child exit!\n"); exit (0); }Else{ close (CONN_FD); }
Linux C My