开发者

Different standard streams per POSIX thread

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, diff开发者_如何学Goerent_thread, NULL);

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

    pthread_join(id, NULL);
    return 0;
}


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.


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.


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.


If you insist on using the standard I/O functions like "printf()" then the only way I can think of that this could be done is for the standard I/O library to support thread-specific I/O using thread-local data structures (similar to the way "errno" is a macro that calls a function that returns the thread-local error number). I don't know of any implementations of standard I/O that do this.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜