I am writing multi-clients chat program of C++, I have a few problems that I can’t solve.
1. When a user comes in, the server will Accept() the client, then assign a socket id to the client. When the client disconnect, another client comes in, after the server Accept() it, the client will get another socket ID. I want to reuse the socket id, but the Accept() will give a larger socket id than previous socket id of previous client. So, How can I assign the socket id to each client?
2. I use select(fdmax + 1, &read_fds, NULL, NULL, NULL) and for(i = 0; i <= fdmax; i++) to scan each every exist connection, and client can use tenlet connect to my server. In addition to chatting, client can run commands(like ls, cat) on my server, my server will use fork() and dup() send the result to the client. Here is a problem, if the user assigns a new PATH of environment variable, the PATH of other clients will be changed too. How can I avoid this, every clients should have their own default PATH value?
For the first problem: you’re probably not closing (
close(2)) the socket (even if the client disconnects). Although I can’t find it in the POSIX spec, typicallyaccept(2)(and pretty much anything creating file descriptors) will return the smallest possible descriptor.That being said, there’s likely no reason to tie your application to this. Your application should treat
acceptas if it could return anything.For the second problem, you should change the
PATHafter you fork, right before youexec.All this aside, I notice you’re tagging your question C++: you should take a look at the mighty asio.