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).


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