in reply to Re^2: Win32::Process::CpuUsage: Redirect output?
in thread Win32::Process::CpuUsage: Redirect output?
Capture::Tiny does not seem to capture XS's stdout, which is what printf() uses. In order to test this one needs a C compiler (I don't know what the procedure is in windows).
First create a test XS module using h2xs -A -n Mytest
cd Mytest and edit the file Mytest.xs and append this at the end:
void hello(fh) INPUT: PerlIO* fh; CODE: printf("Hello, world via printf!\n"); PerlIO_printf(PerlIO_stdout(), "Hello, world via PerlIO_printf +\n"); PerlIO_printf(fh, "Hello, world to provided file-handle\n");
Also create a new file test.pl with this content:
#!/usr/bin/env perl use ExtUtils::testlib; use Mytest; use Capture::Tiny 'capture'; my $fh; open $fh, '>', 'out.txt' or die "open, $!"; my ($out, $err) = capture { Mytest::hello($fh); }; print "out=\n$out\nend out\n"; close $fh;
Compile and run with these 3 commands: perl Makefile.PL followed by make all followed by ./test.pl
The output is:
out= Hello, world via PerlIO_printf end out Hello, world via printf!
And the contents of 'out.txt' are: Hello, world to provided file-handle
The most important thing is that the output produced by plain printf() is not captured. What is captured is the output produced by PerlIO_printf(PerlIO_stdout(), ...) as I suspected - meaning that there are 2 different stdouts...
The example code above demonstrates how to provide a filehandle to an XS sub to print to it. This is IMO the cleanest solution. Whereas your perl script forks and in one strand you call CpuUsage($fh) to write to provided filehandle. And on another strand you tail that filehandle. A fork can be replaced by an alarm. Upon forking, an open filehandle will be duplicated which means that the file cursor will be distinct in the 2 strands and that makes it easy to tail and write at the "same" time. Opening a file for rw can be done using +>.
So, is this a solution? I think yes but you need to be able to compile or post a patch to the author.
The blahblah: I can't understand why write code which does not try to open up lots of possibilities for the user at reasonable/minimal cost for the author. Why printf() when you can fprintf(fh)? And also why write a Perl XS module which does not PerlIO_printf(PerlIO_stdout(),...)?
bw, bliako
|
|---|