Golang setting the time-out for executed scripts (terminating a process started with os/exec in Golang)

Source: Internet
Author: User
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


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.