This is a created article in which the information may have evolved or changed.
Background
Recently in the development of a monitoring module, which needs to use the Golang os/exec package to execute the script, considering that the user-written script may cause the program to block, you need to set a time-out for the execution of the program, it was thought that this is a very simple program, But I did not think that the effect of the implementation is far from what I want (there may be not enough knowledge reserves ... ^ _ ^), so here you want to throw the problem to discuss with everyone.
Scheme
Simply explained below:
If the cmd.wait () function is placed in the main program, once the program is executed here, it will cause the program to block here, waiting for the cmd.wait () function to return. So put the Cmd.wiat () function in another goroutine, and wait for a case event to be triggered by select{}.
Channel done indicates that an external program terminates execution of the shell process.
Channel Errch is returned by the cmd.wait () function.
Execution effect
Test Case:
Script content: echo "Test Shell"
Time-out: 3 s
There seems to be no problem with that.
At this point, modify the contents of the execution script: sleep 10; echo "Test Shell"
, looking at:
As can be seen from the log, the number of goroutine has been increasing, knowing that the first script execution is complete, so the number of goroutine is maintained at 13 this number. From here it can be inferred that using this scheme to set the time-out for executing the program obviously seems problematic, or it is not possible to prevent the program from being kept in a stable state.
If you have a better way, welcome to discuss together ... ^_^
Test code