Reputation:
I have a gateway server and 2 clients.(made in Oracle VM VirtualBox).
In my gateway server, I have listener.c listening all packets.(in a while(1)
loop).
If the client sends a valid token, I have to put it in my authorized MACs list and all packets coming from authorized MACs must be forwarded for 180 secs. (in other words, given internet access for 180 secs).
Before 180 sec., the thing with a single user it was working.
/* authorized MACs list */
char *auth_macs[5];
int client;
pthread_mutex_t lock;
/* after 3 min remove the client from auth list */
void *timer(void *arg){
sleep(180);
pthread_mutex_lock(&lock);
auth_macs[client] = " ";
client--;
pthread_mutex_unlock(&lock);
return NULL;
}
This is how I tried to implement my timer thread. client
is a global variable that changes in main function.
if(has_token == 1){
client++;
sprintf(client_ip, "./accept.sh %s", sender);
system(client_ip);
auth_macs[client] = client_mac;
/* start timer thread */
pthread_t tid;
pthread_create(&tid, NULL, timer,NULL);
pthread_join(tid, NULL);
}
This is where I start this thread. accept.sh
is a shell script to allow forwarding.
My problem is I thought sleep(180)
in timer thread was only going to stop itself. But instead, listener.c
stops receiving packets.
How can I fix this? I want timer to wait 180 secs but still be able to receive packets in main function.
Upvotes: 1
Views: 510
Reputation: 121397
sleep()
only suspends the calling thread. So, it doesn't affect the main thread.
What's problematic is the pthread_join()
call:
pthread_create(&tid, NULL, timer,NULL);
pthread_join(tid, NULL);
This effectively renders the multi-threading pointless. Because there's only thread that's ever going to make progress as the main thread waits until the created thread is completed.
You need to remove pthread_join()
call and possibly it outside the while(1)
loop if main thread needed to join. Alternatively, you can call pthread_exit(0)
outside the thread creation loop so that main completes execution while the rest of the threads, if still alive when main thread
breaks its loop, can continue execution.
Upvotes: 2