0

我坚持以下几点:

我尝试将分叉进程中的“$ua->get($url)”通过管道传输到父进程,如下所示:

use LWP::UserAgent;
use IO::Handle;

pipe my $ua_reader, my $ua_writer;
my $url = "http://some-sample-html-file";

my $ua = LWP::UserAgent->new;
$ua->timeout(1);

my $ua_process = fork();
if( $ua_process == 0 ) {
    close $ua_reader;
    print $ua_writer $ua->get($url);
    exit 0;
}

do {
    $ua_process = waitpid(-1, 0);
} while ($ua_process >= 0);
close $ua_writer;
my $response = $ua_reader->getline;
close $ua_reader;

print $response->decoded_content;

我收到此错误:

Can't locate object method "decoded_content" via package "HTTP::Response=HASH(0x19045f0)" (perhaps you forgot to load "HTTP::Response=HASH(0x19045f0)"?) at ./uafork.pl line 26.

$ua 对象肯定有一个“decoded_content”方法,但它在通过管道后不可调用(其他方法,例如“is_success”也不起作用......)。

这里有什么可能的解决方案?任何帮助将不胜感激。

4

1 回答 1

2

首先,您不能直接将 HTTP::Response 写入流中。该错误表示写为“HTTP::Response...”的字符串没有方法decoded_content。您必须写入从 decoded_content 获得的字符串,并作为字符串读取。

use LWP::UserAgent;
use IO::Handle;
use Encode;

pipe my $ua_reader, my $ua_writer;
my $url = "http://some-sample-html-file";

my $ua = LWP::UserAgent->new;
$ua->timeout(1);

my $ua_process = fork();
if( $ua_process == 0 ) {
    close $ua_reader;
    print $ua_writer encode_utf8 $ua->get($url)->decoded_content;
    exit 0;
}

do {
    $ua_process = waitpid(-1, 1);
} while ($ua_process != 0);
close $ua_writer;
my $response = $ua_reader->getline;
close $ua_reader;

print $response;
于 2013-06-28T09:02:11.773 回答