How can I check the status of the first program in pipeline in Perl's system()?

后端 未结 7 631
小蘑菇
小蘑菇 2021-01-21 06:41
perl -e \'system (\"crontab1 -l\");print $?\'

returns -1 as expected (program crontab1 doesn\'t exist)

perl -e \'system (\"crontab1 -l|         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-21 07:17

    What is the way to check the status of the first (or both) programs?

    There is no such way, at least, not as you have constructed things. You may have to manage sub-processes yourself via fork(), exec() and waitpid() if you must know these things.

    Here is roughly what is happening in your code fragment.

    1. perl's system() spawns a shell, and perl *wait()*s for that subprocess to terminate.

    2. The shell sets up a pipeline:

      1. a subshell *exec()*s grep on the read-end of the pipe
      2. a subshell fails to locate crontab1 anywhere in $PATH, and *exit()*s 127 (on my system, that is, where 127 is the shell indicating failure to find a program to run).
    3. grep detects end-of-file on its input and, having matched nothing, *exit()*s 1.

    4. The shell *exit()*s with the exit code of the last process in the pipeline, which, again, is 1.

    5. perl detects the shell's exit code of 1, which is encoded in $? as 256.
      (256 >> 8 == 1)

提交回复
热议问题