[Q] How to get process information of a running external command ? [os/exec]

xuanbao · · 385 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;m using the &#34;os/exec&#34; package to run a command/process aiming to extract its <strong>memory usage</strong> and <strong>CPU execution duration</strong>. </p> <p>Using the following snippet, i wasn&#39;t able to extract any useful information. I think it&#39;s because the exec.Command has a synchronous call.</p> <pre><code>cmd := exec.Command(&#34;command&#34;, &#34;arg1&#34;, &#34;arg2&#34;) err := cmd.Run() if err != nil { log.Fatal(err) } fmt.Println(&#34;MaxRSS:&#34;, cmd.ProcessState.SysUsage().(*syscall.Rusage).Maxrss) </code></pre> <p>I wonder if i should use a kind of Async exec function or something.</p> <p>I appreciate any help.</p> <hr/>**评论:**<br/><br/>Sythe2o0: <pre><p><code>exec.Command</code> probably isn&#39;t a problem, as it&#39;s just a constructor. If you meant <code>cmd.Run</code>, then you make that into an asynchronous call by wrapping it in a goroutine: </p> <pre><code>go func() { err := cmd.Run() if err != nil { log.Fatal(err) } }() </code></pre> <p>You could do something like this to monitor it: <a href="https://play.golang.org/p/KOu4qB6jEv" rel="nofollow">https://play.golang.org/p/KOu4qB6jEv</a> (I haven&#39;t run this myself, there&#39;s potential errors)</p> <p>Alternatively, from the <a href="https://golang.org/pkg/os/exec/#Cmd.Start" rel="nofollow">docs</a>, use <code>cmd.Start</code></p></pre>nhooyr: <pre><p>Definitely use cmd.Start() otherwise there is a race because you won&#39;t know when the command has started in another goroutine.</p> <p>Waiting for a second does not solve that race, just makes it much less likely.</p></pre>Sythe2o0: <pre><p>Sure, I made an assumption that the print would just print bogus data if the command had yet to start.</p></pre>CipheredBytes: <pre><p>Appreciate that. </p> <ul> <li>Timing can be monitored with <em>cmd.Start</em> and <em>cmd.Wait</em></li> <li>Memory usage can be monitored with <em>cmd.Start</em> or <em>cmd.Run</em></li> </ul></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

385 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传