Dec-26-2025, 01:14 PM
Hi,
1. I have a simple python script named script.py:
read print('Hello') , execute it, and print Hello. But what happens instead is
that the program main hangs.
I have checked the file descriptors with lsof - nothing strange there.
I have checked the hanging main with strace:
but the write() from main does not get there. Even though (as the previous
test (3. above) with script.py has proven) the connection from main to
/usr/bin/python3 works properly.
Can someone please explain what is going on here? My platform is Linux Mint (Ubuntu),
compiler g++, Python 3.10.12.
Thanks,
Jürgen
1. I have a simple python script named script.py:
expr = input() # read an expression from stdin eval(expr) # evaluate the expression2. I start this script from a C/C++ program main.cc:
#include <string.h>
#include <unistd.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <cstdio>
#include <iostream>
using namespace std;
int
main()
{
int spair[2];
socketpair(AF_UNIX, SOCK_STREAM, 0, spair);
const int & parent_sock = spair[0];
const int & python_sock = spair[1];
if (fork()) // parent process (main.cc)
{
close(python_sock); // not used by parent
const char * expr = "print('Hello')\n"; // python expression
write(parent_sock, expr, strlen(expr)); // write it to python's stdin
char buffer[100];
int len = read(parent_sock, buffer, sizeof(buffer)); // python output
buffer[len] = 0;
cout << buffer << endl;
}
else // child process (python3)
{
close(parent_sock); // not used by child
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
dup(python_sock); // stdin
dup(python_sock); // stdout
dup(python_sock); // stderr
char * program = const_cast<char *>( "/usr/bin/python3" );
char * script = const_cast<char *>( "./script.py" );
char * argv[] = { program, script, 0 };
char * env[] = { 0 };
execve(argv[0], argv, env);
}
}3. Not surprisingly, compiling and running main prints Hello:$ ./main Hello4. However, if I remove script.py from argv:
char * argv[] = { program, 0 };then the result should be the same, shouldn't it? The python interpreter shouldread print('Hello') , execute it, and print Hello. But what happens instead is
that the program main hangs.
I have checked the file descriptors with lsof - nothing strange there.
I have checked the hanging main with strace:
strace: Process 16712 attached read(0,So it seems like /usr/bin/python3 blocks on reading stdin (as expected),
but the write() from main does not get there. Even though (as the previous
test (3. above) with script.py has proven) the connection from main to
/usr/bin/python3 works properly.
Can someone please explain what is going on here? My platform is Linux Mint (Ubuntu),
compiler g++, Python 3.10.12.
Thanks,
Jürgen
