简体   繁体   中英

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:]

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

ie 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() ).

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