我有多线程应用程序,我正在创建这样的线程:
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)
现在,在线程的功能,我想重定向stderr和stdout在一个单独的文件为每个线程.像线程日志文件的东西.
我怎么能这样做?
编辑:
如果特定于线程的打印件可以显示在不同的终端上..?我的意思是如果有2个线程则打开2个终端并在不同终端上打印每个线程数据.
如果你真的必须这样做......
首先你需要创建2个pthread_key_t,一个用于stdout,一个用于stderr.这些可以使用创建pthread_key_create,并且必须可以从所有线程访问.让我们把它们stdout_key和stderr_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)
我不推荐这种方法.