473,770 Members | 3,983 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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_SimpleStr ing("foo = 'bar'");
mod = PyImport_AddMod ule("__main__") ;
dict = PyModule_GetDic t(mod);
obj = PyMapping_GetIt emString(dict, "foo");
buffer = PyString_AsStri ng(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_AddMod ule() being
changed to PyImport_Import Module() 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.
Jul 21 '05 #1
2 2346
Quoth MrEntropy <fa**@doesntexi st.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_GetIt emString(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, do**@drizzle.co m
Jul 21 '05 #2
#ifdef def
Donn Cave wrote:
Quoth MrEntropy <fa**@doesntexi st.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.


Though there is probably some solution involving a third party
such as POSIX threads, Linux has a clone(2) procedure which
fork(2) is a macro of. It is tricky to use, but allows for
having the child process have the same pid, memory, memory
mappings, file tables, etc. BSD mmap(2) is more portable and can
be used for interprocess sharing. The solution which Don Cave
provided is probably the one that Mr. Entropy needs to start
with. More specifically, ...

#else

int main (int argc, char **argv)
{
int fd0, fd1, fd2;
{
int fd_in [2], fd_out [2], fd_err [2];
pipe (fd_in); fd0 = fd_in [1];
pipe (fd_out); fd1 = fd_out [0];
pipe (fd_err); fd2 = fd_err [0];
if (!fork ()) {
dup2 (fd_in [0], 0); close (fd0);
dup2 (fd_out [1], 1); close (fd1);
dup2 (fd_err [1], 2); close (fd2);
execl ("python", "python", 0);
perror ("execution failed");
exit (1);
}
}

write (fd0, "print None\n", 11);
write (1, b, read (fd1, b, sizeof (b) /* 5 or more */));

#define write0(q...) write (fd0, "print " #q "\n", \
sizeof (#q) + 5 + 1 - 1)
write0 (True); write (1, b, read (fd1, b, sizeof (b)));
write0 (5, str (5.0), ...);
write (1, b, read (fd1, b, sizeof (b)));
return write0 (True, False, None,
True and False,
True and None,
False and None,
True and False and None) && 0;
}

#endif
Jul 21 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
13084
by: John Lin | last post by:
Howdy, I want to know how to tell if a forked process is done. Actually, my real question is that I want to run a shell script inside of a python script, and after the shell script has finished running, I want to do more stuff *condition* on the fact that the shell script has finished running, inside the same python script. The only way I can think of is to fork a process and then call the
3
2228
by: Greg Lindstrom | last post by:
Hello- I am running python 2.3. on an HP-9000 box running Unix and have a POSIX script that sets up my production environment. I would like to run the script from inside a python routine and pick up the environment variables but am having trouble getting it done. Suppose the script is called setprod. How can I call this from inside a python script then pick up the env's later in my program? I've tried os.system ('setprod') and...
2
4995
by: RL | last post by:
Hello Perl gurus, 1. I have a web page where I can push a button (dospawn.html). 2. This button calls a CGI script (spawnboss.cgi) 3. spawnboss.cgi calls a forking perl script (forkme.pl) 4. forkme.pl calls the process creation script (createme.pl) 5. createme.pl creates my notepad.exe process, but no window shows up on my PC. The result on my web browser is:
1
3478
by: Alexander N. Spitzer | last post by:
I am trying to write a program that will fork a process, and execute the given task... the catch is that if it runs too long, I want to clean it up. this seemed pretty straight forward with a single executable being run from the fork. The problem I am having now is that if I call a shell scripts, then lets say calls "xterm &", after the timeout has occurred, I kill the shell script, but the xterm is still running... I cannot seem to kill...
2
1544
by: James Colannino | last post by:
Hey everyone. I'm writing a small application in Python that uses os.fork() to create a separate process in which another application is run in the background. The problem is that I need to know whether or not that separate application managed to start and return from within the parent appropriately. Here's, roughly, a pseudo example of what I want to do (I know the code itself is not correct): def function(): pid = os.fork()
2
5120
by: gregarican | last post by:
I have an application I'm writing using PyQt. I'm trying to create the various windows by subclassing Qt objects. I have a subclassed QMainWindow as the parent, and then a series of subclassed QWidgets as other child windows that get used. How can I pass variables back and forth between the parent and child windows? For example, if I have a child window that processes a customer lookup I want the retrieved values to be passed back to the...
0
1853
by: dan.jakubiec | last post by:
I'm trying to write a Python app which accepts a socket connection and then spawns another Python process to handle it. I need it to run under both Linux and Windows. I have it working under Linux, but am having problems with the Windows implementation. My app uses the subprocess.Popen class to spawn the child process. The first problem I ran into was that Windows Python won't let you pass a socket object via the Popen stdin argument...
7
1543
by: MD | last post by:
Hi, I would like to access "variables" defined in my Python program in a C module extension for Python. Is this possible? I looked at the Python C API reference but didn't find anything there that could help me. Thanks in advance for any help/tips. Regards, -MD
1
4092
by: scsoce | last post by:
A child thread has a long-time executions, how to suspend it and resume back the orignial place ? I know it' nature to use singal, but child thread cannot get signal as Python Manual say. And i dnt like to check status variable as the long-time executions can not or be dirty to stop to do check.
0
9591
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9425
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10228
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10057
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10002
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8883
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6676
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3970
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2816
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.