Hi,
I have a question related to a TCP server based on BSD socket.
The following program is essentially the same as that in
Rich Stevens' book "UNIX network programming", page 284-285.
If I run this server program in background, when I log off, it
is supposed to exit like other application programs (unless I
use nohup to start the server in background)? Right?
What was happening is that when I logged on later, the server
program was still running and, its parent pid was changed to 1.
(The server became a daemon?)
My question is that why the server did not exit and why it went
to a daemon process itself when I logged off?
Thanks in advance.
<------------------------------------------------------------------->
/*
* Example of server using TCP protocol.
*
*/
#include "inet.h" /* see page 284 of R. Stevens' book */
main(argc, argv)
int argc;
char *argv[];
{
int sockfd, newsockfd, clilen, childpid;
struct sockaddr_in cli_addr, serv_addr;
int status;
pname = argv[0];
/*
* Open a TCP socket (an Internet stream socket).
*/
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
err_dump("server: can't open stream socket");
/*
* Bind our local address so that the client can send to us.
*/
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(SERV_TCP_PORT);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
err_dump("server: can't bind local address");
listen(sockfd, 5);
for ( ; ; ) { /* Always TRUE */
/*
* Wait for a connection from a client process.
* This is an example of a concurrent server.
*/
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
err_dump("server: accept error");
if ( (childpid = fork()) < 0)
err_dump("server: fork error");
else if (childpid == 0) { /* child process */
close(sockfd); /* close original socket */
/* process the request at (newsockfd) */
story(newsockfd); /* do application */
exit(0);
}
close(newsockfd); /* parent process */
if(waitpid(childpid, &status, 0) != childpid){
err_dump("server: can't wait for child");
exit(1);
}
} /* End of the for-loop */
Quote:}