0

Is there any possibility to achieve different redirections for standard output like printf(3) for different POSIX thread? What about standard input?

I have lot of code based on standard input/output and I only can separate this code into different POSIX thread, not process. Linux operation system, C standard library. I know I can refactor code to replace printf() to fprintf() and further in this style. But in this case I need to provide some kind of context which old code doesn't have.

So doesn't anybody have better idea (look into code below)?

#include <pthread.h>
#include <stdio.h>

void* different_thread(void*)
{
    // Something to redirect standard output which doesn't affect main thread.
    // ...

    // printf() shall go to different stream.
    printf("subthread test\n");

    return NULL;
}

int main()
{
    pthread_t id;
    pthread_create(&id, NULL, different_thread, NULL);

    // In main thread things should be printed normally...
    printf("main thread test\n");

    pthread_join(id, NULL);
    return 0;
}
4

4 に答える 4

4

You can do what you want if you create threads using clone, but POSIX.1 says that the threads must share open file discriptors.

There are several tricks you could try, but you really should just convert the calls to the FILE * argument accepting functions.

于 2010-05-19T18:24:51.383 に答える
1

On *nix systems, stdio layers over file descriptors, and file descriptors are global to a process. Thus, there is no way to do what you want without changing something. Your best bet is to rewrite code using fprintf(). Since this involves adding an argument to an arglist, I'm not even sure that you'd be able to use preprocessor trickery to achieve your goals without modifying the actual code.

Maybe you could clarify the reasons that you can't create new processes? The problem may be solvable from that angle.

于 2010-05-19T18:29:44.633 に答える
1

If you have thread-local storage, you could do something like:

#undef printf
#define printf(fmt, ...) fprintf(my_threadlocal_stdout, fmt, __VA_ARGS__)

and likewise for all the other stdio functions you intend to use. Of course it would be better not to try redefining the same names, but instead perform search and replace on the source files to use alternate names.

BTW even without thread-local storage extensions to the compiler, you could use a function call that returns the right FILE * for the calling thread to use.

于 2010-07-26T12:23:59.450 に答える
0

「printf()」のような標準I / O関数の使用を主張する場合、これが可能であると私が考える唯一の方法は、標準I/Oライブラリがスレッドローカルを使用してスレッド固有のI/Oをサポートすることです。データ構造(「errno」がスレッドローカルエラー番号を返す関数を呼び出すマクロである方法と同様)。これを行う標準I/Oの実装を知りません。

于 2010-05-19T18:14:05.007 に答える