简体   繁体   English

Perl管道和C进程作为子进程[Windows]

[英]Perl pipe and C process as child [Windows ]

I want to fork a child ( which is my C executable ) and share a pipe between perl and C process, Is it possible to have STDOUT and STDIN to use as pipe. 我想派生一个孩子(这是我的C可执行文件),并在perl和C进程之间共享一个管道,是否可以将STDOUT和STDIN用作管道。

Tried with following code but child process keep continue running. 尝试使用以下代码,但子进程继续运行。

use IPC::Open2;
use Symbol;
my $CHILDPROCESS= "chile.exe";
$WRITER = gensym();
$READER = gensym();

my $pid = open2($READER,$WRITER,$CHILDPROCESS);
while(<STDIN>)
{
   print $WRITER $_;
}
close($WRITER);
while(<$READER>)
{
    print STDOUT "$_";
}

The Safe Pipe Opens section of the perlipc documentation describes a nice feature for doing this: perlipc文档的“ 安全管道打开”部分描述了一个不错的功能:

The open function will accept a file argument of either "-|" open函数将接受文件参数"-|" or "|-" to do a very interesting thing: it forks a child connected to the filehandle you've opened. "|-"来做一件非常有趣的事情:它派生一个与您打开的文件句柄相连的孩子。 The child is running the same program as the parent. 子进程与父进程运行相同的程序。 This is useful for safely opening a file when running under an assumed UID or GID, for example. 例如,这对于在假定的UID或GID下运行时安全地打开文件很有用。 If you open a pipe to minus, you can write to the filehandle you opened and your kid will find it in his STDIN . 如果打开负号管道,则可以写入打开的文件句柄,您的孩子会在他的STDIN找到它。 If you open a pipe from minus, you can read from the filehandle you opened whatever your kid writes to his STDOUT . 如果从负号打开管道,则可以从打开的文件句柄中读取孩子写给他的STDOUT

But according to the perlport documentation 但是根据perlport文档

open 打开

open to |- and -| 打开|--| are unsupported. 不被支持。 (Win32, RISC OS) (Win32,RISC操作系统)

EDIT: This might only work for Linux. 编辑:这可能仅适用于Linux。 I have not tried it for Windows. 我没有为Windows尝试过。 There might be a way to emulate it in Windows though. 不过,可能有一种在Windows中模拟它的方法。

Here is what you want I think: 我想这就是您想要的:

#Set up pipes to talk to the shell.
pipe(FROM_PERL, TO_C) or die "pipe: $!\n";
pipe(FROM_C, TO_PERL) or die "pipe: $!\n";

#auto flush so we don't have (some) problems with deadlocks.
TO_C->autoflush(1);
TO_PERL->autoflush(1);

if($pid = fork()){
    #parent
    close(FROM_PERL) or die "close: $!\n";
    close(TO_PERL) or die "close: $!\n";
}
else{
    #child
    die "Error on fork.\n" unless defined($pid);

    #redirect I/O
    open STDIN, "<&FROM_PERL";
    open STDOUT, ">&TO_PERL";
    open STDERR, ">&TO_PERL";
    close(TO_C) or die "close: $!\n";
    close(FROM_C) or die "close $!\n";

    exec("./cprogram"); #start program
}

Now you can communicate to the shell via FROM_C and TO_C as input and output, respectively. 现在,您可以分别通过FROM_C和TO_C作为输入和输出与Shell通信。

有关Perlmonks的问题解答表明,只要您足够仔细地管理open2open2可以在Windows上open2运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM