I am running the below script in python2 and python3 environment.
import subprocess as sub
import sys
#import time
import multiprocessing, time, signal
def tcpdump():
p = sub.Popen(('sudo', 'tcpdump', '-l', '-xx'), stdout=sub.PIPE)
for row in iter(p.stdout.readline, b''):
sys.stdout.write(row.rstrip())
def print_hello():
print "yo"
time.sleep(20)
print "goodbye"
def main():
p1 = multiprocessing.Process(target=tcpdump)
p2 = multiprocessing.Process(target=print_hello)
p1.start()
p2.start()
while p2.is_alive():
time.sleep(2)
p1.terminate()
print "We terminated"
#p1.terminate()
#print "one more time"
#print_hello()
#tcpdump()
main()
In python3, its running flawless but in python2 it's giving me an error
tcpdump: Unable to write output: Broken pipe
Can someone know the reason behind this?
PS I changed the print statement before running in python3.
You need to kill the process before leaving the program and remove sudo from the subprocess. This code worked on my machine:
import subprocess as sub
import sys
#import time
import multiprocessing, time, signal
def tcpdump(p):
for row in iter(p.stdout.readline, b''):
sys.stdout.write(row.rstrip())
def print_hello():
print "yo"
time.sleep(5)
print "goodbye"
def main():
p = sub.Popen(('tcpdump', '-l', '-xx'), stdout=sub.PIPE)
p1 = multiprocessing.Process(target=tcpdump, args=(p,))
p2 = multiprocessing.Process(target=print_hello)
p1.start()
p2.start()
while p2.is_alive():
time.sleep(2)
p1.terminate()
p.kill()
print "We terminated"
#p1.terminate()
#print "one more time"
#print_hello()
#tcpdump()
main()
Run this script using sudo and everything should be fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.