Python subprocess.Popen PIPE and SIGPIPE

别说谁变了你拦得住时间么 提交于 2019-12-04 11:37:17
proc1 = subprocess.Popen(['ps', 'cax'], stdout=subprocess.PIPE)

creates this a pipe between the parent process and proc1:

|        |         |       |
| parent |-<-----<-| proc1 |                   
|        | ^       |       |
           |                     
       p1.stdout   

p1.stdout is what the parent would read to obtain (stdout) output from proc1.

proc2 = subprocess.Popen(['grep', 'python'], stdin=proc1.stdout,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)

connects a copy of the pipe from proc1 to proc2:

|        |         |       |         |       |
| parent |-<-----<-| proc1 |->----->-| proc2 | 
|        |         |       |         |       |

By calling p1.stdout.close(), we close the parent processes's side of the pipe:

|        |         |       |         |       |
| parent |       <-| proc1 |->----->-| proc2 | 
|        |         |       |         |       |

Now when proc2 terminates, its side of the pipe is also closed:

|        |         |       |         |       |
| parent |       <-| proc1 |->       | proc2 | 
|        |         |       |         |       |

The next time proc1 tries to write to the pipe, a SIGPIPE signal is generated, which allows proc1 to terminate since it knows no one is listening on the other end of its pipes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!