Listening thread does not print statements - c

I am doing socket programming in C. In essence, I need a server that runs the indefinite listening loop in a separate thread and whenever it accepts a new connection, it must create a new client thread to handle the client's requests.
Below I have the main function that declares a port number and calls the function createListenThread. This function creates a new thread and invokes the function listenLoop.
int main(int argc, char *argv[])
{
int client_port = 6000;
createListenThread(client_port);
}
void createListenThread(int listen_port)
{
pthread_t listen_tid;
printf("In createListenThread\n");
// listenLoop(&listen_port);
if(pthread_create(&listen_tid, NULL, listenLoop, &listen_port) != 0)
socketError("Could not create thread\n");
}
void *listenLoop(void *arg)
{
pthread_detach(pthread_self());
int listen_socket, listen_port, *client_socket, struct_size;
struct sockaddr_in client_addr;
pthread_t client_tid;
listen_port = *((int *)arg);
listen_socket = createSocket(listen_port);
struct_size = sizeof(struct sockaddr_in);
while(1)
{
printf("In ListenLoop\n");
client_socket = malloc(sizeof(int));
*client_socket = -1;
*client_socket = accept(listen_socket, (struct sockaddr *)&client_addr, &struct_size);
printf("Received connection request from (%s , %d)\n",
inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
pthread_create(&client_tid, NULL, starterFunction, client_socket);
}
close(listen_socket);
}
My problem is that whenever I run the server, only "In ListenThread" and "In ListenLoop" is never printed. I have even tried fprintf(stdout, "In ListenLoop") and fflush(stdout) but the statement is still not printed. When I comment out:
if(pthread_create(&listen_tid, NULL, listenLoop, &listen_port) != 0)
socketError("Could not create thread\n");
and simply invoke ListenLoop as follows:
listenLoop(&listen_port);
Both the print statements appear. Is there an obvious mistake in the way I'm creating the thread and invoking the ListenLoop function? Is the function ListenLoop ever executed?
Edit: I ran the program in gdb which printed the following:
In createListenThread
[New Thread 0xb7e30b70 (LWP 10024)]
[Thread 0xb7e30b70 (LWP 10024) exited]
[Inferior 1 (process 10021) exited normally]
Why is the thread exiting??

The problem will be that your main function returns immediately after calling createListenThread. You should wait for your thread function to finish using pthread_join within your createListenThread otherwise the program may terminate before the thread function can finish. Calling pthread_join on your thread will wait until the thread function returns and will therefore definitely get chance to run before main() returns.

I hope that you declare all your functions above main ... But you should really call your listenLoop in main thread. Else, you create a thread to run the loop and main thread passively waits it. And you will not be bothered by argument passing, thread waiting and so on.
listenLoop could then be a true void and no longer a void *, as you do not return anything.
If you were forking a process, it would make sense, since it is the correct way to create a daemon process immediateley adopted by init process, but for threads it is simply useless.

Related

Pthread create is not starting the thread

I’m using pthread to start a thread, but the create function itself is not starting the thread
But instead if i call pthread join, it starts so actually should i call p thread join?
i heard from some answers that pthread join is not required , my pthread create function is called from main
int main(void) {
printf("-----------Welcome------\n");
Start_Generation();
return 0;
}
int Start_Generation(void)
{
ret=pthread_create(&C_AO_GENERATION_THREAD, NULL, C_Aogeneration_thread,(void*) message1);
if(ret!=0)
{
printf("Error Starting Thread\n");
return -1;
}
else
{
printf("AO Thread Started\n");
}
//ret=pthread_join(C_AO_GENERATION_THREAD, NULL);
return 0;
}
void *C_Aogeneration_thread (void *ptr)
{
char *message;
message = (char *) ptr;
unsigned int prof_gen_count;
unsigned int written_sample=0;
unsigned int curr_idx=0;
int ch=0;
int written=0;
printf("%s",message);
printf(" Generation Started\n");
prof_gen_count=(samplingrate/10);
while(stopflag)
{
printf("Thread is working\n");
}
return 0;
}
enter code here
I’m using pthread to start a thread, but the create function itself is not starting the thread
As presented in the question, your main thread terminates by returning from main immediately after reporting on the success or failure of the pthread_create() call, so
the whole program terminates at that point, apparently before the child progresses far enough to present any evidence that it is running, but also
there is no point in using a separate thread.
But instead if i call pthread join, it starts so actually should i call p thread join?
A call to pthread_join() does not return successfully until the specified thread has terminated. That is, in fact, its purpose. As a rule of thumb, you should either join or detach every thread you create. Joining is usually what you want, and note, too, that detaching a thread does not prevent the process from terminating and taking that thread with it when the main thread returns or exit()s.

Why child threads alive after the main threads are killed?

I have written a code where I have created two child threads from the parent thread.
Then, with receiving a signal from another terminal inside those child threads, I printed the threadID and exited the thread.
I have 2 questions.
I'm receiving the signal from the child thread. Why is it printing the threadID of the parent thread?
After killing the parent thread, how can be the child threads alive??
The Code :
void sig_handler(int signo)
{
if (signo == 1){
printf("%d\n", pthread_self());
pthread_exit(NULL);
}
}
void* doSomeThing(void* arg)
{
printf("In function -> %d\n", pthread_self());
if (signal(1, sig_handler) == SIG_ERR)
printf("\ncan't catch SIGHUP\n");
while(1)
sleep(1);
return NULL;
}
int main(int argc, char *argv[])
{
printf("In function -> %d\n", pthread_self());
char *ch1;
pthread_t tid1, tid2;
ch1 = "random";
int ret1, ret2;
ret1 = pthread_create(&tid1, NULL, &doSomeThing, (void *) ch1 );
ret2 = pthread_create(&tid2, NULL, &doSomeThing, (void *) ch1 );
while(1)
sleep(1);
return 0;
}
Here is the image of the output given in terminal :
The first 3 lines are the 3 threadIDs. 1st one is the Main threadIDs, then the two secondary threads.
Then the threadIDs printed from the following block of code.
if (signo == 1){
printf("%d\n", pthread_self());
pthread_exit(NULL);
}
Why is this happening???
Signals are delivered to the process, not to individual threads. So, you can't have a signal handler just for one thread as you are doing here.
What you can do is block signals you are interested in using pthread_sigmask() and let a dedicated thread handle signals using sigwait(), which is the most common way.
In addition, you can only safely call async-signal-safe functions from within a signal handler. From the Linux signal man page:
Async-signal-safe functions
A signal handler function must be very careful, since processing
elsewhere may be interrupted at some arbitrary point in the execution
of the program. POSIX has the concept of "safe function". If a
signal interrupts the execution of an unsafe function, and handler
either calls an unsafe function or handler terminates via a call to
longjmp() or siglongjmp() and the program subsequently calls an
unsafe function, then the behavior of the program is undefined.
The linked man page has a list of functions that are safe to call from within a signal handler. If the function is not on that list, it is unsafe to call it. No exceptions.
Note that neither printf() nor pthread_exit() are on the list of async-signal-safe functions.
And calling pthread_exit() from within a signal handler creates several other problems:
The thread that exits is generally not under any control. In many cases, the signal can be delivered to any thread.
The exiting thread can leave objects in an unknown state - a mutex can be left locked by a thread that no longer exists, for example.
Any thread cleanup handlers registered with pthread_cleanup_push() will also be called from within a signal handler context.

Wait termination of threads work before close a server after receiving SIGINT or SIGTERM (Posix thread in C)

I'm developing a client / server in C using pthread.
It's a card game where server is the dealer between two clients that play.
I have this situation
server.c:
main:
int main (int argc, char * argv[])
using as a thread dispatcher for listening eventually entering connection on accept
pthread_create(&sig_thread, NULL, &thread_signal_handler, &server_Socket );
thread to catch signals (maskered conveniently) created inside main function
pthread_create(&tid[i++], NULL, &worker, (void*) arr_args)
every client is associated to a thread created (tid is the array of thread ID)
pthread_join(sig_thread, NULL)
to join thread for signals
pthread_join(tid[i], NULL)
to join thread created for every client connected.
worker:
void * worker(void * args)
do his job and terminated
thread signal handler:
void * thread_signal_handler(void * arg)
void * thread_signal_handler(void * arg) {
sigset_t set;
int sig, n;
int * socket = (int*) arg;
sigemptyset(&set);
sigaddset(&set, SIGINT);
sigaddset(&set,SIGTERM);
while (server_UP)
{
/* wait for a signal */
if (sigwait(&set, &sig))
perror("Sigwait");
/* received SIGINT or SIGTERM - closing server */
if ((sig == SIGINT || sig == SIGTERM)) {
printf(TERM_SERVER"\n");
server_UP = 0; /* global variable */
/* close socket blocked on MAIN */
shutdown( *socket, SHUT_RDWR );
}
return (void *) EXIT_SUCCESS;
}
In this way, the signal is catched well and the server is terminated immediately.
I need, if there are matches in progress, to waiting that all the workers finish their jobs properly, so I want to know how to say to thread handler "did you receive a SIGINT (or SIGTERM)? Ok, waiting the termination of all workers".
Any suggests? If you need more code, i'll edit this post.
When you create them you can save all of the threads in an array or a list and at the end call pthread_join() on all of them.
while (pthread_list) {
pthread_join(pthread_list->th_id, NULL);
pthread_list = pthread_list->next;
}
If you don't want to keep track of all threads you can keep a count of running threads, increment it before calling pthread_create, decrement the count as each thread finishes.
Then in the handler you'll sleep for some seconds iteratively until the count becomes 0.

Pthread Run a thread right after it's creation

I have a C program in which I use pthread.
I would like newly created threads to run as soon as they are created.
The reason behind this is that my threads have initialisation code to set up signal handlers, and I must be sure the handlers are ready, before my main thread sends some signals.
I've tried doing pthread_yield just after my pthread_create, but without success.
I doubt it makes a difference, but I am running Linux 3.6 on x86_64.
Thanks
If your goal is to have the main thread wait for all threads to reach the same point before continuing onward, I would suggest using pthread_barrier_wait:
void worker(void*);
int main(int argc, char **argv)
{
pthread_barrier_t b;
pthread_t children[TCOUNT];
int child;
/* +1 for our main thread */
pthread_barrier_init(&b, NULL, TCOUNT+1);
for (child = 0; child < TCOUNT; ++child)
{
pthread_create(&children[child], NULL, worker, &b);
}
printf("main: children created\n");
/* everybody who calls barrier_wait will wait
* until TCOUNT+1 have called it
*/
pthread_barrier_wait(&b);
printf("main: children finished\n");
/* wait for children to finish */
for (child = 0; child < TCOUNT; ++child)
{
pthread_join(&children[child], NULL);
}
/* clean-up */
pthread_barrier_destroy(&b);
return 0;
}
void worker(void *_b)
{
pthread_barrier_t *b = (pthread_barrier_t*)_b;
printf("child: before\n");
pthread_barrier_wait(b);
printf("child: after\n");
}
Or you might use a barrier, i.e. call pthread_barrier_wait (early in the routine of each thread, or at initialization in the main thread), to ensure that every relevant thread has reached the barrier (after which some of your threads could do your naughty signal tricks). See this question.

thread termination issue (c programming)

I'm working on an application for Linux in C which uses multiple threads. The threads which are spawned by the main function do most of the work, and therefore usually finish last. I'm seeing some strange behavior, and I believe it's due to the main thread terminating before the spawned threads have a chance to finish their jobs. Here's some sample code to illustrate what I'm talking about:
#define _POSIX_C_SOURCE 200112L
#define _ISOC99_SOURCE
#define __EXTENSIONS__
#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
void
my_cleanup(void *arg)
{
printf("cleanup: %s\n", (char *)arg);
}
void *
thread_stuff(void *arg)
{
printf("thread started\n");
pthread_cleanup_push(cleanup, "running");
if (arg)
pthread_exit((void *)2);
pthread_cleanup_pop(0);
pthread_exit((void *)2);
}
int
main()
{
int err;
pthread_t tid1, tid2;
err = pthread_create(&tid1, NULL, thread_stuff, (void *)1);
err = pthread_create(&tid2, NULL, thread_stuff, (void *)1);
sleep(10); /* change the value here if you want */
return SUCCESS;
}
When this code is run, the message from the cleanup function is printed twice, as it should be, but other times when it is run, I see the message printed only once sometimes, and other times I see it printed three times or not at all. You add in the sleep function in the main function to play with how long it takes the main function to terminate.
What can I do to make the program run as it should? I suspect it has something to do with joining to the children, but I don't entirely understand the concept of a join or how to apply it to this situation.
Thanks in advance!
Yes, you should "join" the threads. "Joining" a thread simply means waiting until the thread has terminated. In other words, you would do
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
to wait until both threads have terminated.
Edit: What to do if you have a child thread which, in turn, creates a "grandchild" thread? As a rule, whoever created the thread should wait for it to terminate ("join" it). So in this scenario, the child thread would call phtread_join on the grandchild thread, and the main thread would call join on the child thread.
I think you want to run pthread_join on each of the threads when your main thread completes -- this makes the main thread stop until the given thread finishes running. Other threads can still complete first though, so running pthread_join on every thread will prevent the main thread from terminiating until all of the others have terminated.
There is a definite problem if main() finishes before the threads it spawned if you don't call pthread_exit() explicitly. All of the threads it created will terminate because main() is done and no longer exists to support the threads.
By having main() explicitly call pthread_exit() as the last thing it does, main() will block and be kept alive to support the threads it created until they are done.
int main()
{
int err;
pthread_t tid1, tid2;
err = pthread_create(&tid1, NULL, thread_stuff, (void *)1);
err = pthread_create(&tid2, NULL, thread_stuff, (void *)1);
sleep(10); /* change the value here if you want */
/* Add the pthread_exit */
pthread_exit(NULL);
return SUCCESS;
}
Refer for more info here

Resources