Reputation: 133
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.
Upvotes: 1
Views: 2114
Reputation: 155487
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
Upvotes: 1