Why after closing a socket using the statement close(sd) we can still write on it?
Another question is how can I be sure that a socket is closed? How do I check it?
I quote the following code that I can't understand how it works the part in red.
Also, I have some questions more about how I can improve the code and understand some details that seem unclear to me.
Sorry, if my questions seem silly to you, but I am new to socket programming.
Code:
...
sd = socket(AF_UNIX, SOCK_STREAM, 0);
if(sd<0) {printf("Socket failure\n"); exit(1);}
sockaddr.sa_family=AF_UNIX;
strcpy(sockaddr.sa_data,"sock"); // Is strncpy a better function to use here?
addrlen=strlen(sockaddr.sa_data)+sizeof(sockaddr.sa_family);
unlink("sock");
if(bind(sd, &sockaddr, addrlen)< 0)
{
exit(1);
}
listen(sd, 3); // I have set the queue = 3. Does it mean that I can do up to 3 forks at the same time?
for(;;)
{
if((ns = accept(sd, &sockaddr, &addrlen))<0)
{
printf("Server accept failure\n");
exit(1);
}
printf("Connect accepted to client\n");
pid=fork();
if (pid==0)
{
read(ns,bufin,10);
printf("Client sends something and I print the bufin: %s \n",bufin);
close(sd); //Close socket sd
printf("I am sending my messages to the client\n");
// this is successful!! why??
write(ns,buf,100); //Write the messages to the socket
close(ns);
exit(0);
}
else close(ns); //close parent's socket
}