Skip to content

Instantly share code, notes, and snippets.

@riywo
Created March 16, 2011 17:41
Show Gist options
  • Save riywo/872908 to your computer and use it in GitHub Desktop.
Save riywo/872908 to your computer and use it in GitHub Desktop.
オレオレperlipcまとめ

See also perlipc - Perl のプロセス間通信 (シグナル, fifo, パイプ, 安全な副プロセス, ソケット, セマフォ) 【perldoc.jp】

単純に実行だけしたい

system "$CMD";

標準入力を操作したい

open $in, "| $CMD";
print $in "hoge";
close $in;

標準出力を操作したい

$ret = `$CMD`;  or  @ret = `$CMD`;

もしくは open $out, "$CMD |"; while ($line = <$out>) { ... } close $out;

両方操作したい

use IO::Handle;

pipe $parent_out, $child_in;
pipe $child_out, $parent_in;
$parent_in->autoflush(1);
$child_in->autoflush(1);

if (my $pid = fork) {
    close $parent_in; close $parent_out;

    print $child_in 'hoge';
    close $child_in;
    while (my $line = <$child_out>) {
        ...
    }
    close $child_out;
    waitpid($pid,0);
} else {
    die "cannot fork: $!" unless defined $pid;
    close $child_in; close $child_out;

    open STDOUT, '>&', $parent_in;
    open STDIN, '<&', $parent_out;

    exec "$CMD" or exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment