在多线程应用程序中,如何根据线程将stderr&stdout重定向到单独的文件中?

Jee*_*tel 3 c linux pthreads

我有多线程应用程序,我正在创建这样的线程:

int main(int argc,char *argv[])
{
    pthread_t thread_id[argc-1];
    int i;
    struct parameter thread_data[argc-1];
    int status;
    for(i=0;i<argc-1;i++)
    {
      thread_data[i].ip_filename = argv[i+1];
      strcpy (thread_data[i].op_filename,argv[i+1]);
      strcat (thread_data[i].op_filename,".h264");
    }

    for(i=0;i<argc-1;i++)
    {
      pthread_create (&thread_id[i], NULL , &thread_function, &thread_data[i]);
    }      
}
Run Code Online (Sandbox Code Playgroud)

现在,在线程的功能,我想重定向stderrstdout在一个单独的文件为每个线程.像线程日志文件的东西.

我怎么能这样做?

编辑:

如果特定于线程的打印件可以显示在不同的终端上..?我的意思是如果有2个线程则打开2个终端并在不同终端上打印每个线程数据.

rod*_*igo 5

我认为这不可能直接实现。stdin/stdout 是全局变量,在线程之间共享,文件描述符也是如此。

您必须创建自己的文件,并将其更改printffprintf.


Emi*_*nus 5

如果你真的必须这样做......

首先你需要创建2个pthread_key_t,一个用于stdout,一个用于stderr.这些可以使用创建pthread_key_create,并且必须可以从所有线程访问.让我们把它们stdout_keystderr_key.

创建线程时:

FILE *err = ..., *out = ...;
pthread_setspecific(stdout_key, out);
pthread_setspecific(stderr_key, err);
Run Code Online (Sandbox Code Playgroud)

然后在你的头文件中:

#define stdout (FILE*)pthread_getspecific(stdout_key)
#define stderr (FILE*)pthread_getspecific(stderr_key)
#define printf(...) fprintf(stdout, ##__VA_ARGS__)
Run Code Online (Sandbox Code Playgroud)

然后使用:

fprintf(stderr, "hello\n");
fprintf(stdout, "hello\n");
printf("hello\n");
Run Code Online (Sandbox Code Playgroud)

我不推荐这种方法.