in reply to Redirecting stdout with threads

You are combining multi-process models, which is generally problematic. After creating a thread, you create a pipe, fork, redirect i/o and then call system, which forks again. When that second fork gets called, it seems that it is twinning the STDOUT (I assume you don't care about STDERR since you never redirect) from the main thread rather than your threaded-then-forked line of control. Why are you trying to use threads when you already have a functional code using forks and pipes? You can certain use something like the following code in place of that threading:

my $pid = fork(); if ($pid == 0) { print "Hello!\n"; } else { execute(); }

Another possibility is to modify your "can't modify" routine to use backticks in place of system and print the output yourself.

Replies are listed 'Best First'.
Re^2: Redirecting stdout with threads
by michi (Novice) on Mar 15, 2009 at 14:54 UTC
    Thanks for your reply.
    Maybe the example looks a bit weird because i deleted all code that isnt necessary to show my problem.
    I want to use threads cause i feel the communication is easier than with processes. If i create process and a pipe for communication this would result in something like
    while (..) { $tmp = <READ_FROM_OTHER_PROCESS> }
    which blocks one of my processes.
    I tried the ipc forks library instead of threads and it works fine.
      Both methods of IPC work, but it's a very good idea to stick with one consistent approach throughout your code. If you would prefer doing the whole thing with threads, I would refer you to threads on Windows. I posted this question when I was learning threads in Perl, including message passing concepts. Since you are worried about blocking operations, you can maintain your fork/pipe approach and use signals to facilitate a timeout on the connection. There are also a number of IPC-modules on CPAN that may help.