擅长:python、mysql、java
<p>我不知道你用的是什么操作系统和shell。我用zsh描述Mac OS X和Linux(bash/sh的行为应该类似)。</p>
<p>当您按下Ctrl+C时,当前终端<a href="http://www.cons.org/cracauer/sigint.html" rel="nofollow">receive the signal SIGINT</a>中前台运行的所有程序。在您的例子中,它是您的主python进程和os.system生成的所有进程。</p>
<p>由os.system生成的进程然后终止其执行。通常当python脚本接收到SIGINT时,它会引发KeyboardInterrupt异常,但是主进程会忽略SIGINT,因为<code>os.system()</code>。Python<code>os.system()</code><a href="http://docs.python.org/2/library/os.html#os.system" rel="nofollow">calls the Standard C function</a><code>system()</code>,这使得调用进程忽略SIGINT(<a href="http://linux.die.net/man/3/system" rel="nofollow">man Linux</a>/<a href="http://developer.apple.com/library/ios/#documentation/system/conceptual/manpages_iphoneos/man3/system.3.html" rel="nofollow">man Mac OS X</a>)。</p>
<p>因此,您的python线程都不接收SIGINT,只有子进程才能获得它。</p>
<p>当删除os.system()调用时,python进程停止忽略SIGINT,您将得到<code>KeyboardInterrupt</code>。</p>
<p>您可以用<code>subprocess.call(["sleep", "10"])</code>替换<code>os.system("sleep 10")</code>。<code>subprocess.call()</code>不会使进程忽略SIGINT。</p>