-
the fork() instruction
hi all,
I have learnt socket programming through BEEJ's .
In that sample client/server program that prints the message "hello world " on the client screen once the connetion is established..:
I cud not inderstand the role of the fork() instruction..
Can some one help me out??
thanks
-
fork() is a linux call that make a duplicate of the current process. So this would make a separate process to handle the new socket while the current one continues listening. fork() is not available in windows, so you may have to resort to some more complex windows thread programming.
-
yes, i do know how the fork() and exec() procedures work...
this is the piece of code:
Code:
while(1) { // main accept() loop
sin_size = sizeof(struct sockaddr_in) ;
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr,&sin_size)) == -1) {
perror("accept");
continue;
}
printf("server: got connection from %s\n ",inet_ntoa(their_addr.sin_addr));
if (!fork()) { // this is the child process
close(sockfd); // child doesn’t need the listener
if (send(new_fd, "Hello, world!\n", 14, 0) == -1)
perror("send");
close(new_fd);
exit(0);
}
close(new_fd); // parent doesn’t need this
}
I think, the program works even without the fork call, as we two sockets, one for listening and on to tranfer data. So, we can use the send() call immediately after the accept() and there is no need to start another process.. Is,there any significant advantage of using the fork() call though??
-
> Is,there any significant advantage of using the fork() call though??
There's a big disadvantage that if you accept a lot of connections quicky, you rapidly run out of process slots in the process table (which is a finite resource).
Also consider that context switches between processes are considerably more expensive than a function call.
In the same vein are threads, which seem like a nice idea on the surface are a PITA if threads ever need to share any information. Thread synchronisation problems will make your average malloc problem look like a walk in the park.
If you want to handle many connections, then read up on the select() function as well. It allows you to monitor many fd's at the same time and return (possibly after a timeout) with those fd's which are either ready to accept more data, or which have data available to be read.