Jeff wrote:
> Hello, I am trying to write a socket program to allow a program on another
> box to run ppp-on on this one without having to telnet into my linux box
> running ip_masq. My program basically goes like this:
>
> socket()
> bind()
> listen()
> and then an accept() loop that first blocks until it gets a connection,
> adn then runs this code:
I take it that you are writing this program primarily for the purpose
of learning how to write a TCP server? Otherwise, you're probably
better off letting inetd do all of the above for you.
> if (!fork()) // what does this line mean? if(fork == 0)?
> {
> send(new_fd, "hello\n", 6, 0);
> close(new_fd);
> while(waitpid(-1,NULL,WNOHANG) > 0);
> }
>
> this came from a socket tutorial, my actual code is a little different
> and includes a recv that prints the first thing it recieves and then
> continues, and it also has some error checking that I left out. I dont
> understand what this is doing. particularly how the fork() function works.
> Could someone explain this?
fork() `clones' the current process. After it has completed
successfully (it returns -1 if it fails), there are two identical
processes running, both of which have just completed the fork() call.
Each process has its own address space, and immediately following the
fork() call, the contents of both processes address spaces will be
identical. The only difference is that fork() returns 0 to the `child'
process, and returns the pid of the child to the parent process.
Both the parent and child processes then run concurrently. If the
parent wishes to wait for the child to complete (which is what happens
if you run a command from the shell without putting an `&' after it),
it needs to use waitpid() (or wait, wait3, wait4) to wait for the
child to terminate.
The above code seems incorrect, i.e. the child is calling waitpid(),
when it should be the parent.
For a TCP server, the parent needs to periodically call waitpid() with
the WNOHANG flag. It will receive a SIGCHLD whenever a child processs
terminates, so it can install a signal handler for SIGCHLD and call
waitpid() from within the signal handler. Alternatively, you can just
execute `while(waitpid(-1,NULL,WNOHANG) > 0);' regularly, e.g. every
time you accept a connection.
Failing to wait for child processes will cause zombie processes
(children which have terminated but haven't been waited for) to
accumulate.
--
Glynn Clements <[EMAIL PROTECTED]>