I'm trying to pipe a pair of Linux commands using python.
Example in Linux terminal:
ls -l | less
Here's a pseudo-code of what I do:
- I define a pipe.
- Fork and make a child for the parent process.
- Set the stdout file descriptor number to the write-end of the pipe.
- Execute the command and Exit.
- Fork another process.
- Set the stdin file descriptor number to the read-end of the pipe.
- Execute the command.
But it's not working.
 child1 = os.fork()
    if child1 < 0:
        raise fork_exception
    elif child1 == 0:
        oread, owrite = os.pipe()
        os.close(oread)
        os.dup2(owrite, sys.stdout.fileno())
        os.dup2(owrite, sys.stderr.fileno())
        os.execvp(command[0][0], args=command[0])
        child2 = os.fork()
        if child2 < 0:
            raise fork_exception
        elif child2 == 0:
            os.close(owrite)
            os.dup2(oread, sys.stdin.fileno())
            os.execvp(command[1][0], command[1])
            sys.exit()
        os.waitpid(child2, 0)
        sys.exit(0)
    os.waitpid(child1, 0)
command is a nested list of piped commands.
command = [["ls", "-l"],["less"]]
p.s 1: I tried making the child2 and child1 two separate children of one parent, but that didn't work either.
p.s 2: I made a temporary file and used it as pipe, and that worked well. But using os.pipe(), It's not working, and I can't find the problem with my code.
Note: I don't want to use os.subprocess() or any other function or system call. I want to make this code, which is implemented using os.fork() and os.pipe(), running.
