Home > Software design >  Program calls printf() then loops forever. Why don't I see the printf output?
Program calls printf() then loops forever. Why don't I see the printf output?

Time:11-07

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <math.h>
  
struct my_Struct{
    int a;
    int b;
};
void *myThreadFun(void *received_struct)
{
    struct my_Struct *struct_ptr = (struct my_Struct*) received_struct;
    printf("%.1lf",pow(struct_ptr->a,struct_ptr->b));
    return NULL;
}
   
int main(int argc, char* argv[])
{
    struct my_Struct s;
    s.a = atoi(argv[1]);
    s.b = atoi(argv[2]);
    
    pthread_t thread_id;
    pthread_create(&thread_id, NULL, myThreadFun, &s);
    pthread_join(thread_id, NULL);
    while(1);
    exit(0);
}

Why does this code do nothing? It is supposed to print statement in the spawned thread and then go into infinite loop.

CodePudding user response:

Using gdb we can see the thread forked successfully

[New Thread 0x7ffff7a2d640 (LWP 8261)]
[Switching to Thread 0x7ffff7a2d640 (LWP 8261)]

Thread 2 "a.out" hit Breakpoint 1, myThreadFun (received_struct=0x7fffffffd960) at tmp.cpp:15

If you delete the while(1) you can find the output. The delay in output may related to the stdio's buffer, while(1) prevented the buffer from flushing.

You can try another approach: add fflush(stdout); after printf, this works the same.

CodePudding user response:

It's because stdout buffers whole lines, so it means it won't print your values until you do one of three things:

  • end your string with \n: printf("%.1lf\n", ...)
  • flush the stdio buffer: fflush(stdout)
  • terminate the program (it will flush all buffers automatically)
  • Related