Gray
Gray

Reputation: 297

Can someone explain this Python code for me?

This code create pty (pseudo-terminals) in Python. I have commented the parts that I do not understand

import os,select
pid, master_fd =os.forkpty() #I guess this function return the next available pid and fd 
args=['/bin/bash']
if pid == 0:#I have no I idea what this if statement does, however I have noticed that it get executed twice
    os.execlp('/bin/bash',*args)
while 1:
    r,w,e=select.select([master_fd,0], [], [])
    for i in r:
        if i==master_fd:

            data=os.read(master_fd, 1024)
            """Why I cannot do something like 
               f=open('/dev/pts/'+master_fd,'r')
               data=f.read()"""
            os.write(1, data) # What does 1 mean???
        elif i==0:

            data = os.read(0, 1024)
            while data!='':
                n = os.write(master_fd, data)
                data = data[n:]

Upvotes: 0

Views: 216

Answers (1)

Adam
Adam

Reputation: 17379

In Unix-like operating systems, the way to start a new process is a fork. That is accomplished with fork() or its several cousins. What this does is it duplicates the calling process, in effect having two exactly the same programs.

The only difference is the return value from fork(). The parent process gets the PID of the child, and the child gets 0. What usually happens is that you have an if statement like the one that you're asking about.

If the returned PID is 0 then you're "in the child". In this case the child is supposed to be a shell, so bash is executed.

Else, you're "in the parent". In this case the parent makes sure that the child's open file descriptors (stdin, stdout, stderr and any open files) do what they're supposed to.

If you ever take an OS class or just try to write your own shell you'll be following this pattern a lot.


As for your other question, what does the 1 mean in os.write(1, data)?

The file descriptors are integer offsets into an array inside the kernel:

  • 0 is stdin
  • 1 is stdout
  • 2 is stderr

i.e. that line just writes to stdout.

When you want to set up pipes or redirections then you just change the meaning of those three file descriptors (look up dup2()).

Upvotes: 4

Related Questions