erlang 调用shell 命令

时间:2022-10-26 21:49:19

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

[plain] view plain copy
  1. 1> os:cmd("pwd").  
  2. "/home\n"  

不过os:cmd/1是不能获知外部程序的退出状态的,比如外部程序是正常退出还是异常退出。怎么获知外部程序的退出状态呢?可以用erlang:open_port/2,比如: [plain] view plain copy
  1. 1> erlang:open_port({spawn, "erlc"}, [exit_status]).  
  2. #Port<0.573>  
  3. 2> flush().  
  4. Shell got {#Port<0.573>,{exit_status,0}}  
  5. ok  
  6. 3> erlang:open_port({spawn, "erlc a.erl"}, [exit_status]).  
  7. #Port<0.584>  
  8. 4> flush().                                                 
  9. Shell got {#Port<0.584>,{data,"a.erl:none: no such file or directory\n"}}  
  10. Shell got {#Port<0.584>,{exit_status,1}}  
  11. 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).