Reading variables from a forked child (Python C/API)

Donn Cave donn at drizzle.com
Fri Jul 15 11:46:12 EDT 2005


Quoth MrEntropy <fake at doesntexist.dud>:

| 	I'm having a little trouble getting an idea running. I am writing a C 
| program which is really a frontend to a Python program. Now, my C 
| program starts up, does some initialisation like initialisation of it's 
| variables and Py_Initialize() and then it fork()s. After forking the 
| child launches the python program with Py_Main() and with the parent I 
| want to be able to read the variables of the Python program. I have 
| tried many ways but cannot find a solution to do this.

That's because there is no solution.  After a fork, the only effect
observable in the parent process is the return value of fork, which
will have a non-zero value.  Subsequent execution in the child process
occurs completely independently from the parent, and leaves no trace
whatever.  So you can't read variables from memory, that were set by
the child.

Past that, I deleted the rest of your post because it sort of avoids
the question of what you're really trying to accomplish and what errors
you actually got, but note that just for the sake of avoiding segmentation
faults etc., it's a good idea when writing in C to check return values:

	obj = PyMapping_GetItemString(dict, "foo");
	if (obj) {
		...
	} else {
		...
	}

Anyway, if you really need a subprocess, you're going to have to
communicate with it via some sort of I/O, like UNIX pipes or temporary
files or something.  You probably don't need to call Python from C,
may as well just invoke python (cf. os.spawnv)

	Donn Cave, donn at drizzle.com



More information about the Python-list mailing list