NPE
NPE

Reputation: 500893

ipython and fork()

I am planning a Python script that'll use os.fork() to create a bunch of child processes to perform some computations. The parent process will block until the children terminate.

The twist is that I need to be able to run the script both from the Unix shell using python and from ipython using %run.

In what manner should the child processes terminate to avoid breaking back into the ipython command prompt? In my experience, sys.exit() won't do.

Upvotes: 8

Views: 1776

Answers (2)

NPE
NPE

Reputation: 500893

The following seems to work:

import os, sys

child_pid = os.fork()
if child_pid == 0:
  print 'in child'
  os._exit(os.EX_OK)
  print 'hm... wasn''t supposed to get here'
else:
  print 'in parent'

The trick is to use os._exit() instead of sys.exit(). The documentation contains the following passage:

Note The standard way to exit is sys.exit(n). _exit() should normally only be used in the child process after a fork().

Upvotes: 9

salezica
salezica

Reputation: 77099

In Linux terminology, instead of forking the iPython process, why don't you exec a regular python interpreter from the iPython shell and have that one fork?

Upvotes: 0

Related Questions