I am trying to print a message every 20 seconds in a multithreaded program. I have a server that has two threads. One thread waits for incoming connections and makes a new thread for the client when it connects.
I have looked at this: C: SIGALRM - alarm to display message every second but with my code, I'm not sure where I would put the loop. I am not allowed to make a new thread or use sleep() or any variation of sleep().
Code for server acceptor thread:
while((csock = accept(sock, (struct sockaddr *) &theClient, (socklen_t *) &cl)))
{
pthread_t newClient;
new_sock = malloc(sizeof(socket_t));
*new_sock = csock;
pthread_create(&newClient, NULL, getInput, (void *) new_sock)
}
The other thread is just handling the client's input. I tried putting the loop inside the above loop but then it never accepts new connections.
How would I go about doing this? Any help would be appreciated.
Your problem seems to be currently that accept() is blocking the thread until a new connection comes in; therefore you can't print anything.
You could use non-blocking accept() in a loop to check for connections, and in the same loop wait until 20 seconds has passed. Note that this is very inefficient as this loop doesn't stop; it uses 100% of 1 cpu core.
// sock is listening
fcntl(sock,F_SETFD,O_NONBLOCK);
time_t tm = time(); // Unix timestamp, in seconds.
while(true) {
csock = accept(sock, (sockaddr*)&theClient, (socklen_t*)&cl);
if (csock==-1) {
if (errno==EAGAIN || errno==EWOULDBLOCK); // No connection at the
// moment, we need to try
// again later.
else break; // Some other error occurred
}
else { // If it is connected
pthread_t newClient;
new_sock = malloc(sizeof(socket_t));
*new_sock = csock;
pthread_create(&newClient,NULL,getInput,(void*)new_sock);
}
if (time()-tm>=20) { // At least 20 seconds have elapsed since
// last message.
printf("Hello World!!\n");
tm = time(); // Start waiting for another 20 seconds.
}
}
Using select() to wait for a new connection would be far more efficient - you can also set a timeout which expires so that you can print your message
Edit: You don't want to use a signal, because, as it says in the article you linked, you can't use printf from inside a signal handler.
If you use the signal handler to set a flag, you won't be able to read the flag unless you use non-blocking accept() (because otherwise accept() could block for a minute but nothing prints).
Related
Background: My code structure: I have a master socket on main thread, then each time a new client is coming, the threadpool will be notified and let one pre allocated thread take the task.
Inside this thread, I will pass a slave socket to it, and let it using accept call to listen to the client.
Scenario: In my thread pool, thread A is listening to a client right now, now I want to stop all the pre-allocated thread and close all the connection to the client, the main thread is trying to close the connection using close the connection to the client, and trying to terminate thread A using pthread_join.
main() {
// create threadpool
// logic to create mastersocket
startServer(masterSock)
IwantToCloseServer() // this function is not directly called in main, but simulated by a terminal signal , like kill -quit pid.
}
int startServer(int msock) {
int ssock; // slaveSocket
struct sockaddr_in client_addr; // the address of the client...
unsigned int client_addr_len = sizeof(client_addr); // ... and its length
while (!stopCondition) {
// Accept connection:
ssock = ::accept((int)msock, (struct sockaddr*)&client_addr, &client_addr_len); // the return value is a socket
// I was trying to replace this line of code to poll(), but it's not does the same thing as before
if (ssock < 0) {
if (errno == EINTR) continue;
perror("accept");
running =0;
return 0;
// exit(0);
} else {
// push task to thread pool to deal with logic
}
// main thread continues with the loop...
}
return 1;
}
IwantToCloseServer(slaveSocket) {
// when i want to close() or shutdown() function to close connections, these 2 function always return -1, because the thread is blocked on accept call
// logic try to terminate all the preallocated threads, the pthread_join function is stuck because the thread is blocked on accept
}
Problem: The thread A is keeping blocking on the ::accept function , the close and shutdown function return -1, they won’t close the connection , and the pthread_join is not keep going because thread A is blocked on accept.
Things I tried:
I have try to change my while loop related accept function, for example, set a flag stopCondition,
while(!stopConditon) {
ssock = ::accept((int)msock, (struct sockaddr*)&client_addr, &client_addr_len);
}
However, when the main thread change stopCondtion, the thread A is blocked inside the accept function.
It won’t go inside the while loop, so this solution won’t affect the accept function, it’s not working
I have also tried to send a signal to this blocked Thread A, using
pthread_cancel or pthread_kill(Thread A, 9)
However, if I do this, the whole process gets killed.
3.try to use poll() to replace the line, where the accept functions at, with a timeout
however, the program doesn't behave like before, the program can't listen to client anymore.
How do I terminate thread A (which is blocked on accept function call right now), so that I can clean this pre allocated thread and restart my server ?
btw i can not use library like boost in my current program. And this is under linux system not winsocket
to check periodically stopConditon in your while(!stopConditon) { first call accept/pool with a timeout to know if there is something new about msock, then depending on the result call accept etc else do nothing
I was trying to replace this line of code to poll()
try to use poll() to replace the line, where the accept functions at, with a timeout
you cannot replace accept by poll, you have to call accept / pool first and of course check the result then may be call accept
Out of that
while(!stopConditon) {
if(!stopCondtion) {
is redundant and can be replaced by
while(!stopConditon) {
I wrote a small tcp server, which creates a new thread for each incoming connection:
while (server_running)
{
client_sock = accept(server_sock,
(struct sockaddr *)&client_name,
&client_name_len);
if(!server_running)
break;
if (client_sock == -1)
continue;
/* accept_request(client_sock); */
if (pthread_create(&newthread , NULL, &accept_request, &client_sock) != 0)
perror("pthread_create");
}
After about 380 successfull connections, the error message
'pthread_create:cannot allocate memory'
occurs on every new connection attempt. I really don't have a clue where this comes from, since accept_request runs properly. I also noticed that there are many connections with status TIME_WAIT during the run (I used netstat for this). So where could something be going wrong?
When your thread exits, it still hangs around in memory. By default a thread on linux consumes 8 or 10MB of stack, so with 380 threads, you might use nearly 4GB of virtual memory - which might hit a limit on your system.
To have a thread be disposed when it is finished executing , you need to call pthread_join() on that thread, or you can make the thread a 'detached' thread. A detached thread will automatically be disposed when it ends execution. You can add
pthread_detach(pthread_self());
to the start of your accept_request() thread function to make it a detached thread.
As a side note, you have a race condition on the call to
pthread_create(&newthread , NULL, &accept_request, &client_sock)
Here you pass &client_sock to the thread, a local variable. If you have 2 clients connecting to your server at almost the same time, the last one will overwrite the client_sock variable, and 2 of your threads will see the same file descriptor. You could e.g. rather do this:
int *new_fd = malloc(sizeof *new_fd);
*new_fd = client_sock;
pthread_create(&newthread , NULL, &accept_request, new_fd)
And make sure your accept_request thread free()'s the passed in argument.
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.
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.
I am trying to implement a multithreaded UDP server by creating thread.
The following method is used for creating thread.
pthread_create(&threadID, NULL, ThreadMain, threadArgs);
ThreadMain method is,
void *ThreadMain(void *threadArgs) {
pthread_detach(pthread_self());
int sock = ((struct ThreadArgs *) threadArgs)->sock;
free(threadArgs);
HandleUDPClient(sock);
return (NULL);
}
In the HandleUDPClient method is like this,
void HandleUDPClient(int sock) {
struct sockaddr_storage clntAddr; // Client address
// Set Length of client address structure (in-out parameter)
socklen_t clntAddrLen = sizeof(clntAddr);
// Block until receive message from a client
char buffer[MAXSTRINGLENGTH]; // I/O buffer
// Size of received message
ssize_t numBytesRcvd = recvfrom(sock, buffer, MAXSTRINGLENGTH, 0, (struct sockaddr *) &clntAddr, &clntAddrLen);
...
...
When I am creating socket and running the HandleUDPClient method it handles requests from client perfectly. But when I am trying to use thread, after entering the HandleUDPClient method it does not process the recvfrom method. Actually it does not wait for the client to receive any request. Program just terminates.
Can anybody tell me why this problem occurring and how can I resolve it?
The problem is that you detach your threads, meaning that you will not have to wait for your threads to exit. Instead the main program continues its work, until it reaches its end and then exit, with no regard for the (detached) threads still running.
Either don't detach the threads, and use pthread_join to "join" the threads, or use pthread_exit from the main thread to make sure it will wait for all detached threads to finish.
i have a problem with a multi-thread SMTP/POP3 server. The server starts a pool of threads to handle incoming connections. The main thread create the sockets and the the threads, passing the sockets as parameters in a proper structure. The loop function for the threads is the following:
SOCKET SMTP_ListenSocket = (SOCKET) data->SMTPconn;
SOCKET POP3_ListenSocket = (SOCKET) data->POP3conn;
static struct sockaddr_in ClntAddr;
unsigned int clntLen = sizeof(ClntAddr);
hEvents[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
hEvents[1] = CreateEvent(NULL, FALSE, FALSE, NULL);
hEvents[2] = exitEvent; //HANDLE FOR A MANUAL RESET EVENT
WSAEventSelect(SMTP_ListenSocket, hEvents[0], FD_ACCEPT);
WSAEventSelect(POP3_ListenSocket, hEvents[1], FD_ACCEPT);
while(1){
DWORD res = WaitForMultipleObjects(3, hEvents, FALSE, INFINITE);
switch(res){
case WAIT_OBJECT_0: {
ClientSocket = my_accept(SMTP_ListenSocket,(struct sockaddr *) &ClntAddr,&clntLen);
/* ... */
my_shutdown(ClientSocket,2);
my_closesocket(ClientSocket);
ClientSocket = INVALID_SOCKET;
break;
}
case WAIT_OBJECT_0 + 1: {
ClientSocket = my_accept(POP3_ListenSocket,(struct sockaddr *) &ClntAddr,&clntLen);
/* ... */
my_shutdown(ClientSocket,2);
my_closesocket(ClientSocket);
ClientSocket = INVALID_SOCKET;
break;
}
case WAIT_OBJECT_0 + 2:
{
exitHandler(0);
break;
}
}//end switch
}//end while
When the pool contains only one thread there's no problem. When the pool consist of more threads, only one thread accepts the incoming connections
Do you have the pooled threads all calling this same code? If so, then don't use WaitForMultipleObjects() (or WSAWaitForMultipleEvents()) like this. This kind of model only works reliably if one thread is polling connections. If you have multiple threads polling at the same time, then you have race conditions.
Instead, you should use AcceptEx() with Overlapped I/O or Completion Ports instead. The thread that creates the sockets can call AcceptEx() on each socket to queue a new operation on each one, then the pooled threads can use GetQueuedCompletionStatus() or GetOverlappedResult() to dequeue a pending connection without worrying about trampling on other threads. Once a connection is accepted, the receiving thread can process it as needed and then call AcceptEx() to queue a new operation for that socket.
Each thread here is setting a new WSAEventSelect prior to entering the wait. This overwrites any existing event selects. This means that, once a thread (call it thread A) accepts a connection, there is no event associated with the socket.
To solve this, you should call WSAEventSelect again within your switch, immediately after the accept(). This will restore the event binding immediately before going into any potentially lengthy processing.
Note that it's possible that two threads may be awoken for the same event, if the timing works out just right. You can hack around that by going back to your wait loop if the accept fails, but this is a bit unsatisfying.
So, instead of rolling your own version, use IO completion ports here. I/O completion ports have a number of additional features, and avoid potential race conditions in which two threads might pick up the same event. They also take steps to reduce context switches when your code is not CPU bound.