开发者

Redirect stdout/stderr for each thread

I like to redirect output from stdout for each thread to a file. The following code redirect all thread output to a single file -

int fd = open(<filename_threadid.txt>, <flags>)
_dup2(fd, 1)
开发者_StackOverflow社区

How should I restore the original stdout so the next thread can reliably map its stdout to the filename_threadid?


On all platforms the standard streams (stdin, stdout, stderr) are per process. As such they cannot be redirected per thread. You should modify your code so that each thread outputs to a specific file instead of the stdout.


I use a fork() inside the thread for redirect the stdout of the forked process while the "true" thread is in waitpid(). The problem is how to pass the file where you want to redirect stdout. I use a global thread pool, and the thread will find itself through pthread_equal(pthread_self(),iterator), then in the global thread pool structure there is the outfile where the program should redirect the stdout. In my case I create a tmpnam() and write it to the thread struct, but you can use it how you wish.

Here is some example code: (written on the fly)

pthread_t *t_cur=NULL;
int i,pid,newout;
char *outfile=NULL;

for(i=0;i<MAX_THREADS;i++)
  if(pthread_equal(pthread_self(),globals.tpool[i]->thread))
    break;
if(i==MAX_THREADS)
{
   printf("cannot find myself into global threads pool.\n");
   pthread_exit(&i);
 }
if(globals.tpool[i]->outfile == NULL) //  redirect stdout only if outfile is not set ( this is specfic for my purposes )
{
  outfile = globals.tpool[i]->outfile = malloc(L_tmpnam*sizeof(char));
  tmpnam(outfile);
}

if((pid = fork()) == 0)
{
   if(outfile!=NULL)
   {
     newout = open(outfile,O_CREAT | O_APPEND, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
     dup2(newout,STDOUT_FILENO);
     close(newout);
   }
   /* your code here */
}
else
  waitpid(pid,NULL);
pthread_exit(&i);

I really wrote it on the fly, I haven't tested this code, so take care to fix any errors. I didn't post my real code because of calls to my own library. Here I didn't check the return values from tmpnam(), fork(), open() and malloc(), which you should do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜