简体   繁体   中英

How can I launch multiple programs in a pipe?

Hello everyone I am trying to do the following: Create two children who imitate this command

cat <infile | wc -c> outfile

using

./a.out infile "cat" "wc -c" outfile

For that, I do a pipe at the beginning so that in the first child I dup2 (fd [1], 1); then I run

| execve (argv [2], ARGS, envp) |

in ARGS we have {"/ bin / cat", "infile", "NULL"};

So in the second child, I have the output of the previous program in fd [0], however I have no idea how to use it in order to pass it back as input to the wc-c.

  1. Open infile for reading.
  2. Open outfile for writing.
  3. Create a pipe.
  4. Fork.
  5. If in newly created child,
    1. Clone (using dup2 ) infile 's descriptor onto fd 0.
    2. Clone (using dup2 ) the writer end of the pipe onto fd 1.
    3. Close infile 's descriptor.
    4. Close outfile 's descriptor.
    5. Close the reader end of the pipe.
    6. Close the writer end of the pipe.
    7. Exec cat .
  6. Fork.
  7. If in newly created child,
    1. Clone (using dup2 ) the reader end of the pipe onto fd 0.
    2. Clone (using dup2 ) outfile 's descriptor onto fd 1.
    3. Close infile 's descriptor.
    4. Close outfile 's descriptor.
    5. Close the reader end of the pipe.
    6. Close the writer end of the pipe.
    7. Exec wc -c .
  8. Close infile 's descriptor.
  9. Close outfile 's descriptor.
  10. Close the reader end of the pipe.
  11. Close the writer end of the pipe.
  12. Wait for the first child.
  13. Wait for the second child.

Error checking is left to you.

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