[英]Concurrent Input and Output in Perl
最近我開始學習管道以獲得樂趣。 我已經陷入了幾個部分,但是我認為它很大程度上已經找到了,但我無法弄清楚如何獲得輸入以轉發到程序並同時從該程序輸出。
目前我有這個處理管道的Perl腳本:
#!/usr/bin/perl
use strict;
use warnings;
use threads;
use FileHandle;
use IPC::Open2;
my $cv_program = "./test"; #test is the compiled C program below
my $cv_message = "";
my $cv_currentkey = "";
my $pid = open2(*PIN, *POUT, $cv_program);
my $thread_pipeout = threads->create('PIPEOUT', \&PIN);
$thread_pipeout->detach();
while($cv_currentkey ne "\n")
{
$cv_currentkey = getc(STDIN);
$cv_message .= $cv_currentkey;
}
print POUT $cv_message;
sub PIPEOUT
{
my $PIN = shift;
while(<PIN>)
{
print $_;
}
}
然后我有這個C程序只輸出一些東西,請求一個字符串,然后打印該字符串:
#include <stdio.h>
int main(int argc, char const *argv[])
{
char input[100] = {0};
printf("This is a test.\n");
fgets(input, 100, stdin);
printf("You entered %s\n", input);
return 0;
}
運行Perl腳本的輸出是:
~/Programming/Perl Pipes$ ./pipe.pl
Hello
This is a test.
You entered Hello
注意它在輸入時會阻塞,然后在一個塊中打印出所有內容。 我需要它打印這是一個測試,然后等待實際程序的輸入。
另外我要注意的是我在Perl腳本中使用getc而不是STDIN的原因是因為我找不到讓STDIN不阻止test.c的輸出的方法,但getc在這方面效果不好時刻要么。
我認為問題主要出在C端,而不是Perl端。 C看到它的標准輸出是一個管道,因此在查詢標准輸入之前確保它刷新其標准輸出緩沖區並不是非常謹慎。
要解決此問題,您應該只需添加以下行:
fflush(stdout);
在第一次printf
和fgets
之前。
(免責聲明:未經測試。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.