user1688175
user1688175

Reputation:

Opening an application via C

I am trying to write a simple C PROGAM which EXECUTE a Python SCRIPT (and let it running...) and closes itself.

I tried the following commands but in both cases the C PROGRAM is still alive...

popen("sudo python /home/pi/main.py", "r");
system("sudo python /home/pi/main.py");

Thanks!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Edited !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

I tried this command based on your comments but no success:

char *argv[] = {"/home/pi/main.py"};
execv("sudo python", argv);

Anyone could help? Thanks!

!!!!!!!!!!! Edit 2 !!!!!!!!!!!!!!

This is how I compile it:

gcc -Wall restart.c -o safekill

This is the C program

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

my_popen(char cmd[])
{
    FILE *fp;
    char path[1035];

    fp = popen(cmd, "r");

    if (fp == NULL)
    {
        printf("Failed to run command\n");
        exit(1);
    }

    //Read the output a line at a time - output it
    while (fgets(path, sizeof(path)-1, fp) != NULL)
    {
        printf("%s", path);
    }

    pclose(fp);

}

int main()
{
    my_popen("sudo killall python");
    sleep(1);
    my_popen("sudo killall raspivid");
    sleep(1);

    if(fork())
        printf("Am I here?");
        return 0;

    char *file = "restart";
    char *argv[] = {file, "-c", "sudo python main.py", NULL};
    execvp(file, argv);
}

Result: It prints am I here and doesn't start the python. It is so frustrating.... :-(

Upvotes: 1

Views: 946

Answers (1)

moooeeeep
moooeeeep

Reputation: 32512

You need to add the filename of the program itself to the argument list (argv[0]) and terminate the argument list with a NULL pointer.

Example:

#include <stdlib.h>
#include <unistd.h>

int main() {
    if(fork())
        return 0;
    char *file = "python";
    char *argv[] = {file, "-c", "import time; time.sleep(5); print 'Hello'", NULL};
    execvp(file, argv);    
}

Expected behavior: Immediate (parent) program termination and a short Hello printed 5 seconds later by the child.

Maybe you need to workaround the sudo somehow, but this should get you started.

Upvotes: 1

Related Questions