I have a C program. I want it to run and stop at specific points, and let a python script do some things while it is stopped.
What I did was to put this line at the stopping points in the C program:
kill(getpid(), SIGSTOP);
If my python code has this line:
subprocess.call("./prog");
It is stuck forever, because the C program is never terminated.
If I use this:
subprocess.Popen("./prog");
It resumes before the code section was done.
How can I check if the subprocess is stopped? Or is there another solution? It is very important for me to keep the C program running.
Thank you, Marina
I don't know what's your purpose, if you want to check a subprocess' status, use Popen.poll()
, if you want to wait for it to stop, use Popen.wait()
.
Or you need to check its status periodically? If so, try threading.Timer()
.
To synchronize the execution of your Python script with the child C process, you could use communication eg, write a byte to stdout putchar('\\0')
in C program in the place where you want it to stop and wait while Python does something and try to read back a char getchar()
to continue execution and in reverse in the Python script: read a byte, start doing something, and write byte to signal C program to continue:
from subprocess import Popen, PIPE
# start child process, do not block Python
p = Popen("./prog", stdin=PIPE, stdout=PIPE, bufsize=0)
while p.poll() is None: # while C program is running
# block here until C program writes a byte and flushes its stdout buffer
if not p.stdout.read(1): # EOF
break
# .. do something while C program waits
p.stdin.write(b'\0') # signal C program to continue
To unbuffer stdout in C, call at the very beginning of the C program:
setvbuf(stdout, NULL,_IONBF,0);
Otherwise Python program won't see any output until you call fflush()
explicitly or the corresponding buffer overflows.
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.