Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to shift bits "$? >> 8" when using Perl system function to execute command

Tags:

shell

perl

I have seen this in many places in Perl scripts:

system("binary");
$exit_code = ($? >> 8)
exit($exit_code)
  1. Why should I use this? Is there an alternative way?

  2. I am calling some binary in system(binary) which I created in C++, which does some stuff and if it fails it gives assert. When I reboot a Linux machine, the stuff which is going fails, and my binary generates assert as expected. But on the Perl side where I called it, it throws a 134 error code, which after 134 >> 8, becomes 0. Ultimately it is making my failure operation a success (which I don't want).

like image 560
Dipak Avatar asked Mar 15 '16 09:03

Dipak


People also ask

What does system command do in Perl?

Perl's system() function executes a system shell command. Here the parent process forks a child process, and then waits for the child process to terminate. The command will either succeed or fail returning a value for each situation.

What is the return value of system in Perl?

Perl's System Command It returns 0 if the command succeeds and 1 if it fails. These return values are the inverse of most commands, which typically return 0 when they fail and 1 when they succeed.


1 Answers

perldoc -f system snippet:

The return value is the exit status of the program as returned by the wait call. To get the actual exit value divide by 256.

You can check all the failure possibilities by inspecting $? like this:

$exit_value  = $? >> 8;
$signal_num  = $? & 127;
$dumped_core = $? & 128;
like image 56
sotona Avatar answered Nov 15 '22 00:11

sotona