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

MrEntropy fake at doesntexist.dud
Fri Jul 15 17:56:16 EDT 2005


Greetings,
	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. The ONLY testcase 
in fact that I could get working is this:

#include <Python.h>
#include <stdio.h>

int main(){
   char* buffer;
   PyObject* mod;
   PyObject* dict;
   PyObject* obj;

   Py_Initialize();

   PyRun_SimpleString("foo = 'bar'");
   mod = PyImport_AddModule("__main__");
   dict = PyModule_GetDict(mod);
   obj = PyMapping_GetItemString(dict, "foo");
   buffer = PyString_AsString(obj);
   printf(buffer);
   Py_Finalize();
   return 0;
}

And that only proves to me that I can get the variables out of python, 
nothing to do with forking. When i try doing very much the same thing to 
a forked child I get sedfaults. In other words the child gets 
Py_Main()'d and executes the child, while in the parent i do much the 
same as the above with the exception of PyImport_AddModule() being 
changed to PyImport_ImportModule() because main is already preset i gather.

So my questions are these:

Does the fact that I initialise before the fork have anything to do with 
my failure? And if so, is it because some pointers are invalidated?

Is the problem to do with the inability to perform operations on a 
python environment initialised through C while it's executing? Because 
i'm technically executing operations on it from the parent while the 
child in the same environment is running the program.

In the program that the child is running, i need to access some 
variables it has in __main__. main also has an instantiated object 'd' 
which i also need some variables from, i.e. __main__.d.foo. How can I 
access these?

Overall, I would REALLY appreciate an example of how to do what I want 
to achieve, examples help me a lot so if you wouldn't mind typing one up 
or pointing me to some relevant documentation i'd appreciate it.

Thankyou.



More information about the Python-list mailing list