I'm using a Raspberry Pi and I need to be able to execute a python program once my C program finishes running a function. I've been trying to use fork and exec, however, when I use "python3" as the first parameter for the exec function, all I get is the python command prompt in the console.

- 143,180
- 12
- 188
- 271

- 113
- 1
- 3
- 13
-
Please show the code you tried. – cleblanc Sep 11 '18 at 18:39
-
2Prediction: The Python script you want to run takes no arguments, and you failed to pass `python3` twice to one of the `execl*` functions, or failed to pass it as the first element of `argv` for one of the `execv*` functions, so it ended up interpreting the command as "run `python3` with no arguments, just tell it it has the same name as my script", not "run `python3` under its own name, with my script as its argument". – ShadowRanger Sep 11 '18 at 18:44
-
1@ShadowRanger I failed to pass python3 twice, Thank you very much. – Miguel Ángel Gárate Fox Sep 11 '18 at 18:50
-
I concur with @ShadowRanger, that it's difficult to do more than a prediction without additional information. I'd add that depending on how you are making the call out to the shell, if you in fact **are** passing the path to the python script as the second argument, you may be in the wrong working directory and it won't be able to find the script -- leaving the console to hang. Good luck! – Edwin Sep 11 '18 at 18:50
1 Answers
To answer the problem as determined in the comments:
The OP was using execlp
or the like, in the form:
execlp("python3", "name_of_script.py", (char*)0);
(or if they didn't know about the issue with NULL
, they might have passed NULL
instead of (char*)0
).
Problem is, execlp
usually needs the first argument to be passed twice; the second time it's the value to be set as argv[0]
, while user-supplied arguments are almost always checked for in argv[1]
and higher (the value in argv[0]
is rarely used, and when it is, it's mostly for usage/debug output). When python3
sees its own argv
, it sees that it's been invoked with the "name" of name_of_script.py
, but it doesn't see it as a real "argument", so it acts as if it were launched with no arguments, which leads to the interactive interpreter.
The fix is to pass the program name twice, once to find the program, once to set it in argv
, so the argument is recognized by python3
as a script to invoke:
execlp("python3", "python3", "name_of_script.py", (char*)0);
// ^ program to find
// ^ name to set in argv[0]
// ^ script name to put in argv[1] so script is run

- 143,180
- 12
- 188
- 271