简体   繁体   中英

os.pipe() forcing me to write an input

I have code in python which I modify the stdin and stderr, it work succesfuly but at the end of the program it asks for input (for the shell) python code:

import os
import subprocess

stdin_read, stdin_write = os.pipe()
stderr_read, stderr_write = os.pipe()

os.write(stdin_write, b'\x00\x0a\x00\xff')
os.write(stderr_write, b'\x00\x0a\x02\xff')

subprocess.Popen(["./prog"],stdin=stdin_read, stderr=stderr_read)

code in c (prog.c)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    char buf[4];
    read(0, buf, 4);
    if(!memcmp(buf, "\x00\x0a\x00\xff", 4)){
        printf("success -A \n");
    }

    read(2, buf, 4);
    if(!memcmp(buf, "\x00\x0a\x02\xff", 4)){
        printf("success -B \n");
    }

    return 0;
}

I typed the echo "hello world"

terminal-prove

I was expecting the program to end and not let me write input to the shell. Do I need to close the pipe I created? What should I do so that this won`t happen to me?

Notice the Python program ended before printing success -A and success -B . Apparently ./prog started, then Python ended, then ./prog printed its thing. The pipe still exists until all programs that have access to it close it (or end) so ./prog can still read the data from both pipes.

You typed the echo command into the shell prompt after python ended. It's still the same prompt even though ./prog printed two lines in the middle, between the prompt and your command.

If you want Python to wait for ./prog to finish you can do that:

my_proc = subprocess.Popen(["./prog"],stdin=stdin_read, stderr=stderr_read)
my_proc.wait()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM