1

I saw these code in a book Programming Python:

import os

parm = 0
while True:
    parm += 1
    pid = os.fork()
    if pid == 0:                                             # copy process
        os.execlp('python', 'python', 'child.py', str(parm)) # overlay program
        assert False, 'error starting program'               # shouldn't return
    else:
        print('Child is', pid)
        if input() == 'q': break

Why there are two pythons in os.execlp? And it seems that the second one can be any string. What does the second argument do?

Edit: I still don't understand after reading the possibly duplicated question. This is child.py:

import os, sys
print('Hello from child', os.getpid(), sys.argv[1])

So argv[1] is str(parm), argv[0] is child.py, isn't it?

hgajshb
  • 227
  • 2
  • 7

2 Answers2

0

The first python is the name of the executable to run, the second is the value of argv[0].

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • But http://docs.python.org/3/library/sys.html?highlight=sys.argv#sys.argv says sys.argv[0] is the script itself, how come the second python is argv[0]? – hgajshb Aug 31 '13 at 19:09
0

It's its name, that's why it can be any string.

See http://docs.python.org/3/library/os.html?highlight=os.exec#process-management

The document is not structured well, people could have ignored the second paragraph simply because they jump straight to os.exec* thinking contents above are not relevant.

hgajshb
  • 227
  • 2
  • 7