I wrote a small server program. I wanted to see how it is handling multiple requests. So I wrote the following program to simulate multiple clients.
Pseudo Code:
main()
{
//set up all necessary data structures to connect to the server
fork();
fork();
fork();
create_socket();
connect()
//more code
}
Is there a better way of doing it? What tools I can use to test multi threaded program in C(at least the basic functionality)?
You’ve basically created a “process-fan” with this approach, so yes, that can work, although it’s not threading … you’re actually creating new processes. Therefore you will want, in order to prevent zombie child processes, to “wait” for all processes to complete in each process that has spawned a new process. You could do this with the following line at or near the end of your
main()for all processes that have calledfork()(i.e., include the child-processes as well since they are spawning additional processes):This will wait for all the child-processes the current process has spawned, while preventing any early returns of
wait()due to your process catching a signal. When there are no remaining child-processes for the current process, thenwait()will return-1and seterrnotoECHILD, thus exiting the while-loop.