erlang調用外部程序如何得到其退出狀態

轉載請註明,來自:http://blog.csdn.net/skyman_2001

經常會有erlang程序調用外部程序的需求,比如調用shell命令程序,一般是用os:cmd/1,比如:

1> os:cmd("pwd").
"/home\n"

不過os:cmd/1是不能獲知外部程序的退出狀態的,比如外部程序是正常退出還是異常退出。怎麼獲知外部程序的退出狀態呢?可以用erlang:open_port/2,比如:

1> erlang:open_port({spawn, "erlc"}, [exit_status]).
#Port<0.573>
2> flush().
Shell got {#Port<0.573>,{exit_status,0}}
ok
3> erlang:open_port({spawn, "erlc a.erl"}, [exit_status]).
#Port<0.584>
4> flush().                                               
Shell got {#Port<0.584>,{data,"a.erl:none: no such file or directory\n"}}
Shell got {#Port<0.584>,{exit_status,1}}
ok

關於上面的exit_status:

When the external process connected to the port exits, a message of the form {Port,{exit_status,Status}} is sent to the connected process, where Status is the exit status of the external process. If the program aborts, on Unix the same convention is used as the shells do (i.e., 128+signal).


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章