0

Code fragment inside call(argv) function

if '|' in argv:

  # Split argv into two commands, lst[0] and lst[1]
  r,w=os.pipe()
  pid=fork()

  # Parent
  if pid >0:
    os.close(w)
    os.dup2(r,0)
    run(lst[0])
    os.close(r)
    os.wait()

  # Child
  if pid==0:
    os.close(r)
    os.dup2(w,1)
    run(lst[1])
    os.close(w)
    os._exit(1)

The code above gives the result from a simple pipeline of only two commands, but it causes the shell to exit prematurely. How can I get this code to stop exiting my script and have it return to command prompt?

How the program works

The child executes the second command. Its output is sent to the pipe by using the dup2() call to redirect the output along the pipe. This is accomplished through changing pipeline write file descriptor with the value sys.stdout.

The parent then uses input redirection with the dup2() call. This produces the final output which is then displayed on screen, but directly after the script exits.

The run function call takes in the command and its arguments. It executes the command given. It also runs globing and input and output redirection.

It's probably something simple, but I can't seem to spot what's causing the problem...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • In shell, `parent | child` would write from left to right, from parent to child. In your code it is backwards. why is the direction of output reversed? What is `run()`? You should probably put `close()` immediately after `dup2()`. – jfs Dec 15 '13 at 09:51
  • what happens if you use `close(w if not pid else r); execlp(lst[not pid], lst[not pid])` instead of `run()`? – jfs Dec 15 '13 at 20:55

0 Answers0