Phiber Phiber - 5 months ago 21
C Question

No blocking thread

I have read this and this post on stackoverflow, but no one of them give me what I want to do.

In my case, I want to create a Thread, launch it and let it running with no blocking stat as long as the main process runs. This thread has no communication, no synchronization with the main process, it do his job fully independent.

Consider this code:

#define DAY_PERIOD 86400 /* 3600*24 seconds */
int main() {
char wDir[255] = "/path/to/log/files";

// do other things, this things let the main process runs all the time.
// just segmentation fault, stackoverflow, memory overwrite or
// somethings like that stop it.

return 0;

/* Create and launch thread */
void compress_logfiles(char *wDir)

pthread_t compressfiles_th;

if (pthread_create(&compressfiles_th, NULL, compress, wDir))
fprintf(stderr, "Error create compressfiles thread\n");
if (pthread_join(compressfiles_th, NULL))
//fprintf(stderr, "Error joining thread\n");

void *compress(void *wDir)
// Do job to compress files
// and sleep for one day
sleep(DAY_PERIOD); /* sleep one day*/
return NULL;

With ptheard_join in compress_logfiles function, the thread compresses all files successfully and never returns because it is in infinite while loop, so the main process still blocked all the time. If I remove ptheard_join from compress_logfiles function, the main process is not blocked because it don't wait thread returns, but the thread compresses one file and exit (there a lot of files, arround one haundred).

So, is there a way to let main process launch compressfiles_th thread and let it do his job without waiting it to finish or exit?
I found pthread_tryjoin_np and pthread_timedjoin_np in Linux Programmer's Manual, it seems that pthread_tryjoin_np do the job if I don't care of the returned value, it is good idea to use it?

Thank you.


Please note that the main process is daemonized after call to compress_logfiles(wDir), perhaps the daemonization kill the main process and re-launch it is the problem?


When you fork a new process, only the calling thread is duplicated, not all threads.

If you wish to daemonize, you need to fork first, then create your threads.

From the man page for fork:

The child process is created with a single thread--the one that called fork(). The entire virtual address space of the parent is replicated in the child, including the states of mutexes, condition variables, and other pthreads objects; the use of pthread_atfork(3) may be helpful for dealing with problems that this can cause.