Reputation: 13
Basically I've got two sockets that I'd like to run in parallel, so I don't have to wait for one socket to send data to receive data from the other etc. I can do this easily by forking, but, to be tidier, I'd like to know if there is a way to do it from the same process.
Something like:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void test(){
sleep(5000);
}
int main(int argc, char *argv[])
{
printf("%d\n",time(NULL));
test();
printf("%d\n",time(NULL));
system("PAUSE");
return 0;
}
But both lines of output would be the same, as the sleep function is being processed 'somewhere else'.
I found an MSDN document about creating threads, but it talked about C-library functions not being safe for it, which worried me, I like my stdlib!
So, yeah, if you have any examples, you can just use sleep() as a placeholder, I'm pretty good with sockets :) I'm on Windows, but a Unix version would be nice as well, or better yet, one that works with both.
EDIT: Thanks for all your responses. I think I see what you mean: I have my two sockets, then I call select(), it returns all the sockets that are ready to receive/send data, I send/receive my data, then loop back. However, how could I implement this with accept(), as the socket hasn't yet been created?
Upvotes: 1
Views: 280
Reputation: 51019
I don't know if it works (or has an analog) on Windows, but there's always select.
Upvotes: 0
Reputation: 400049
The easiest approach is to make the sockets non-blocking, and use select()
and/or WaitForMultipleObjects()
to check for when you can read/write more data from/to each socket. That way the application can remain single-threaded while still appearing to service multiple sockets at the same time.
Upvotes: 3