gokuraku has asked for the wisdom of the Perl Monks concerning the following question:

Monks,
I'm working on a TCP listener that I am trying to set so that it stays alive until all the clients that connect to it are disconnected, one way I am doing this is by keeping track of the number of clients. I originally did this as a global value, but realized it was not proper Perl so I made it a local variable, but when I try to pass it into the while loops I have I am not getting the correct count.
What I have is something like this:
while ($client = $server->accept( )) { $clientCount = &add_Clientcount($clientCount); (adds 1) # fork off a child while (defined(my $data_recv = <$client>)) { # Do various things some of which depends on # the client count, one this is a disconnect on # a data string sent which then subtracts the # client from the total count $clientCount = $subt_Clientcount($clientCount); (subtracts 1) # There can be a kill, which will stop the listener # but only if on the disconnect the total number of # clients is 0, I don't want to kill it if a # client is still connected } }
Note: the add and subt functions do manipulate the client count and return the value at the end so it goes into the function and comes out with the proper counts, I know that works properly.

What I get is the total number of clients increments at the beginning of the first while loop, and when it exits stays the same, even if the second while loop manipulates it with the subt_ClientCount function. What I would like to happen is if I have a client count of 1 at the beginning of my first while loop, within the second while loop I subtract the client when disconnecting so my count stays the same.

What I am unsure of is do I need to use a reference to client count within the second while loop so that when that client disconnects the right count is saved? Or is there a better way to handle this?

Thanks!

Replies are listed 'Best First'.
Re: Another Pass By Reference question
by kyle (Abbot) on Jun 13, 2008 at 13:15 UTC

    I can't tell for sure, but it looks as if you increment in the parent and decrement in the child. When you fork, the child is a copy of the parent. What it does to its variables has no effect on the parent. Using a reference for your counter won't help this because it would still be a reference to the child's copy of the counter. What you'll need to do is have the parent do the decrement when it waits for the child.