2010-04-28 105 views
7

爲什麼當我將Perl中的退出代碼$ ?,在Perl中移位8位時,我預計它會變爲-1時是255?爲什麼在Perl中退出代碼255而不是-1?

+6

也許你可以解釋爲什麼你期望退出代碼是-1。 – 2010-04-28 02:25:19

+3

請顯示Perl代碼。什麼程序/腳本'發出'退出代碼,哪個腳本報告它? – lexu 2010-04-28 02:27:01

+4

'perl -e「exit -1」; echo $?'=> 255。 – jrockway 2010-04-28 04:29:13

回答

20

'wait()'返回的退出狀態是一個16位的值。在這16位中,高位8位來自'exit()'返回值的低8位 - 或者從main()返回的值。如果程序自然死亡,則16的低8位全部爲零。如果程序因信號而死亡,則低位8位將對信號編號進行編碼,並指示是否發生核心轉儲。對於一個信號,退出狀態被視爲零 - 類似shell的程序傾向於將低位非零解釋爲失敗。

15  8 7  0 Bit Position 
+-----------------+ 
| exit | signal | 
+-----------------+ 

大多數機器實際上將32位整數中的16位值存儲起來,並且這是用無符號算術處理的。如果進程用'exit(-1)'退出,則16的高階8位可能全爲1,但當向右移位8位時,該進程將顯示爲255。

如果您確實想將該值轉換爲帶符號的數量,則必須根據第16位做一些位調換。

$status >>= 8; 
($status & 0x80) ? -(0x100 - ($status & 0xFF)) : $status; 

又見SO 774048SO 179565

0

你在哪個方向移動它?請提供一個代碼示例。

也:

perldoc -f system 

給出瞭如何處理$做一個很容易理解的例子嗎?

此外,http://www.gnu.org/s/libc/manual/html_node/Exit-Status.html

退出值應255之間0和你的換檔與如何負值由計算機實際上是存儲應該給一些見解組合。

+0

我正在向右移動8位 – syker 2010-04-28 05:14:27

10

的Perl中相同的方式爲C運行時庫的宏WEXITSTATUS,其具有在wait(2)下面的描述返回一個子流程退出代碼:

 
    WEXITSTATUS(status) 
      evaluates to the least significant eight bits of the return code 
      of the child which terminated, which may have been set as the 
      argument to a call to exit() or as the argument for a return 
      statement in the main program. This macro can only be evaluated 
      if WIFEXITED returned non-zero. 

重要這裏部分是至少顯著八位。這就是爲什麼你得到255的退出代碼perlvar手冊頁介紹$?如下:

 
    $?  The status returned by the last pipe close, backtick (‘‘) com- 
      mand, successful call to wait() or waitpid(), or from the sys- 
      tem() operator. This is just the 16-bit status word returned 
      by the wait() system call (or else is made up to look like it). 
      Thus, the exit value of the subprocess is really ("$? >> 8"), 
      and "$? & 127" gives which signal, if any, the process died 
      from, and "$? & 128" reports whether there was a core dump. 

這裏沒有特殊的處理在退出代碼負數。

+0

太棒了! – syker 2010-04-28 05:15:01