1

I cannot figure out how I can execute a python script from my C code. I read that I can embed the python code inside C, but I want simply to launch a python script as if I execute it from command line. I tried with the following code:

char * paramsList[] = {"/bin/bash", "-c", "/usr/bin/python", "/home/mypython.py",NULL};
pid_t pid1, pid2;
int status;

pid1 = fork();
if(pid1 == -1)
{
    char err[]="First fork failed";
    die(err,strerror(errno));
}
else if(pid1 == 0)
{  
    pid2 = fork();

    if(pid2 == -1)
    {
        char err[]="Second fork failed";
        die(err,strerror(errno));
    }
    else if(pid2 == 0)
    {  
           int id = setsid();
           if(id < 0)
           {
               char err[]="Failed to become a session leader while daemonising";
            die(err,strerror(errno));
           }
           if (chdir("/") == -1)
           {
            char err[]="Failed to change working directory while daemonising";
            die(err,strerror(errno));
        }
        umask(0);

        execv("/bin/bash",paramsList); // python system call          

    }
    else
    {        
        exit(EXIT_SUCCESS);
    }
}
else
{    
    waitpid(pid1, &status, 0);
}

I don't know where the error is since if I replace the call to python script with the call to another executable, it works well. I have added at the beginning of my python script the line:

#!/usr/bin/python

What can I do?

Thank you in advance

1
  • Can you skip the bash call entirely and just call python, like this? Commented Jul 26, 2014 at 17:59

2 Answers 2

3

From the Bash man page:

-c string   If the -c option is present, then commands are read
            from string. If there are arguments after the string,
            they are assigned to the positional parameters,
            starting with $0.

E.g.

$ bash -c 'echo x $0 $1 $2' foo bar baz
x foo bar baz

You, however don’t want to assign to the positional parameters, so change your paramList to

char * paramsList[] = { "/bin/bash", "-c",
                        "/usr/bin/python /home/mypython.py", NULL };
Sign up to request clarification or add additional context in comments.

Comments

1

Using char * paramsList[] = {"/usr/bin/python", "/tmp/bla.py",NULL}; and execv("/usr/bin/python",paramsList); // python system call caused a successful invocation of the python script named bla.py

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.