<p>I wrote an app that terminates the browser after 10 minutes. I want to display a desktop notification using <code>notify-send</code> and <code>os/exec</code>. However the notification is never displayed. Here's the code</p>
<pre><code>package main
import (
"os/exec"
"time"
"github.com/shirou/gopsutil/process"
)
func main() {
ticker := time.NewTicker(5 * time.Second)
for range ticker.C {
terminateBrowser()
}
}
func terminateBrowser() {
pids, _ := process.Pids()
for _, pid := range pids {
p, _ := process.NewProcess(pid)
name, _ := p.Name()
if name == "firefox" || name == "chrome" {
go func(p *process.Process, name string) {
time.Sleep(10 * time.Minute)
p.Terminate()
exec.Command("notify-send", name, name+" quit unexpectedly").Run()
}(p, name)
}
}
}
</code></pre>
<p>edit:
i figured it out. i changed <code>exec.Command("notify-send", name, name+" quit unexpectedly").Run()</code> to <code>exec.Command("notify-send", name, name+" quit unexpectedly").Start()</code> so that it wont wait for it to complete.</p>
<hr/>**评论:**<br/><br/>driusan: <pre><ol>
<li>Your main function is likely terminating before the go routine gets scheduled. If you need to use goroutines, consider using a sync.WaitGroup in terminateBrowser.</li>
<li>You're not running the command. See the examples in the go docs of os/exec for how to use exec.Command</li>
</ol></pre>newbgopher: <pre><ol>
<li>the <code>main</code> function is not terminating since it has a <code>ticker</code> that ticks every five seconds. if you run the code, you'll see that it doesn't exit unless you press <code>CTRL+C</code>. I'll try to add a <code>sync.WaitGroup</code>.</li>
</ol>
<p>2 . didn't you see the <code>Run()</code> call at the end?</p></pre>driusan: <pre><p>Oh, sorry. reddit cut off the Run call in the div on mobile unless you manually scroll over. It literally cut it off at the <code>)</code> after the Command argument..</p></pre>newbgopher: <pre><p>no worries fam</p></pre>printf_hello_world: <pre><p>You probably just need to wait for the termination goroutines to finish before exiting the main function.</p>
<p>I'd probably do this with a sync.WaitGroup</p>
<p>Could pass a *sync.Waitgroup into your function, call Add(1) on it, and call Done() on it in the goroutine as it returns.</p>
<p>Then just call Wait() after your loop in main.</p></pre>0xjnml: <pre><blockquote>
<p>However the notification is never displayed.</p>
</blockquote>
<p>Check and handle errors.</p></pre>newbgopher: <pre><p>i log those errors in my code, i just remove it here for brevity. there's no error logged when i ran it though.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传