<p>The following code works fine if Firefox is running, but if it finds nothing from <code>pidof</code> (I've also tried <code>pgrep</code>) then it takes the error path:</p>
<pre><code>fx := exec.Command("pidof", "firefox")
firefoxPid, err := fx.CombinedOutput()
if err != nil {
somethingBroke(err, string(firefoxPid))
}
if firefoxPid != nil {
notify("Firefox PID: ", string(firefoxPid))
}
</code></pre>
<p>I would expect both of the assignments to be <code>nil</code> in the event of no process being found, but instead <code>err</code> is apparently assigned <code>exit status 1</code>. What have I missed?</p>
<hr/>**评论:**<br/><br/>dlq84: <pre><p>On UNIX-like systems, when a command succeeds it usually return exit status 0, otherwise it returns any other number. pidof has exit status 1 when it can't find any processes with that name. I would definitely expect err to be exit status 1.</p>
<p>you can test this in bash:</p>
<pre><code>$ pidof <non-existing-process>
$ echo $?
1
$ pidof <existing-process>
32726 32707 352 348
$ echo $?
0
</code></pre>
<p>From the MAN file:</p>
<pre><code>EXIT STATUS
0 At least one program was found with the requested name.
1 No program was found with the requested name.
</code></pre></pre>Xychologist: <pre><p>Aha, so not a Go problem at all. Thank you. I had (naively, it seems) assumed that correctly returning nothing when nothing was present would count as a success.</p></pre>karma_vacuum123: <pre><p>good way to think of it - there is only one success case but many reasons for an error....so unix-y systems use 0 as a default success valueto easily discriminate</p></pre>mister_zurkon: <pre><p>I once had an afternoon of pain writing shell scripts when I naively assumed/misremembered that the exit status of 'find' would be the number of files found. Nope. Gotta look up these things.</p></pre>tgulacsi: <pre><p>Try running "pidof firefox; echo $?"
As pidof exists with 1 as the exit státus, which indicates error.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传