PDA

View Full Version : [SOLVED] Working with os module (python)



wingnut2626
October 23rd, 2013, 02:37 PM
I have this script :


while True:
parm += 1
pid = os.fork()
if pid == 0:
os.execlp('espeak', 'espeak','this is parm number'+str(parm))
assert False, 'error starting program'
else:
print('Child is',pid)
if input() == 'q' : break


And it does say 'This is parm number (parm)' And it does print Child is (pid). Im confused as to how this works though. How is the pid of os.fork() == 0? Whenever I run os.fork() from the interpreter it is never 0......

Vaphell
October 23rd, 2013, 02:53 PM
http://docs.python.org/2/library/os.html#os.fork

wingnut2626
October 23rd, 2013, 03:12 PM
are there any conditions in which the child process id would not be 0?

wingnut2626
October 23rd, 2013, 03:33 PM
another question. Why does

os.fork, os.pid

result in 2 tuples of 2 items each?

Bachstelze
October 23rd, 2013, 03:44 PM
Uh, and what is your problem, exactly? Based on what you say, the program seems to work as expected...

Vaphell
October 23rd, 2013, 04:01 PM
fork clones the code and the data, with the difference that in the original (parent) you get a non-zero value, while in the child you get 0. The difference allows you to recognize in which parallel 'universe' you are - child gets to run through the pid==0 branch and parent goes through else


parent | child
-----------------------------------------------
pid = os.fork() | pid = os.fork()
if pid == 0: | if pid == 0:
stuff | stuff
else: | else:
stuff | stuff

http://www.python-course.eu/forking.php

wingnut2626
October 23rd, 2013, 04:26 PM
Vaphell I owe you a beer (or whatever). Thanks so much

wingnut2626
October 23rd, 2013, 04:27 PM
So even though its miliseconds (or nano seconds) , it appears the parrent if/else block would execute first.....

spjackson
October 23rd, 2013, 06:23 PM
So even though its miliseconds (or nano seconds) , it appears the parrent if/else block would execute first.....
What makes you think that? The if and else branches are executed in separate processes, and to all intents and purposes these are concurrent.

Bachstelze
October 23rd, 2013, 08:33 PM
What makes you think that? The if and else branches are executed in separate processes, and to all intents and purposes these are concurrent.

This point bears repeating (and emphasis). As it is, there is no way to predict which instruction (print or espeak) will be executed before the other. Assuming that one or the other will run first is a major mistake (called a race condition), which can have serious consequences. If for some reason you need to ensure that one or the other will run first, there are some mechanisms like mutexes which will let you achieve that, but unless you use such a mechanism, you must not assume either way.