fork() and STDOUT/STDERR to the console from child processes

前端 未结 2 1306
-上瘾入骨i
-上瘾入骨i 2021-02-09 10:55

I\'m writing a program that forks multiple child processes and I\'d like for all of these child processes to be able to write lines to STDERR and STDOUT

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-09 11:35

    While this doesn't help your garbleness, it took me a long time to find a way to launch a child-process that can be written to by the parent process and have the stderr and stdout of the child process sent directly to the screen (this solves nasty blocking issues you may have when trying to read from two different FD's without using something fancy like select).

    Once I figured it out, the solution was trivial

    my $pid = open3(*CHLD_IN, ">&STDERR", ">&STDOUT", 'some child program');
    # write to child
    print CHLD_IN "some message";
    close(CHLD_IN);
    waitpid($pid, 0);
    

    Everything from "some child program" will be emitted to stdout/stderr, and you can simply pump data by writing to CHLD_IN and trust that it'll block if the child's buffer fills. To callers of the parent program, it all just looks like stderr/stdout.

提交回复
热议问题