Exit 1 on assigning 'nil'

blov · · 222 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>The following code works fine if Firefox is running, but if it finds nothing from <code>pidof</code> (I&#39;ve also tried <code>pgrep</code>) then it takes the error path:</p> <pre><code>fx := exec.Command(&#34;pidof&#34;, &#34;firefox&#34;) firefoxPid, err := fx.CombinedOutput() if err != nil { somethingBroke(err, string(firefoxPid)) } if firefoxPid != nil { notify(&#34;Firefox PID: &#34;, 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&#39;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 &lt;non-existing-process&gt; $ echo $? 1 $ pidof &lt;existing-process&gt; 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 &#39;find&#39; would be the number of files found. Nope. Gotta look up these things.</p></pre>tgulacsi: <pre><p>Try running &#34;pidof firefox; echo $?&#34; As pidof exists with 1 as the exit státus, which indicates error.</p></pre>

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

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