Open application in the background in C - Linux

Asked

Viewed 556 times

2

I am programming a watchdog for my system, at the beginning of the code I need to run the application in the background, for this I use the command:

system(". /meuprogram&");

But the program understands the '&' (necessary to open process in the background) as a parameter expected by the application.

The command ". /myprogram&" executed directly by the terminal works correctly, but in C this problem is occurring.

The important thing is to be able to open my application in the background and continue the execution of the watchdog. Any ideas? Thanks!

  • I think the solution will be a little more complex. You should use Fork() with exec() routines. Give a search on this. If I have time, put an answer. But for that I need to test and there is the lack of time. : -) See this: http://stackoverflow.com/questions/8319484/regarding-background-processes-using-fork-and-child-processes-in-my-dummy-shel

1 answer

2


I implement the following code (based on other codes, I no longer have their source) that does more or less what you want.

The code is to carry out the fork process and then change the execution session of the same, so that the parent process can be terminated without the child process being closed. Thus, the child process becomes orphaned. It is equivalent to the functioning of a daemon:

    pid_t pid = 0;
    pid_t sid = 0;

    pid = fork();
    if ( pid < 0 ) {
            puts("Falha ao criar o processo filho.");
            return -1;
    }

    if ( pid > 0 ) {
            puts("Eu sou o proceso pai! Hora de finalizar!");
            return 0;
    }

    umask(0);
    sid = setsid(); // altera a sessão.
    if ( sid < 0 ) {
            return -2; // falha ao alterar a sessão.
    }

    int dummy = chdir("/"); // retorno não utilizado... deveria checar por erros ;D

    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

The command chdir("/"); change the working directory of the process. You can use another directory. In my case, I left the "/" because the process runs in an environment of chroot.

  • If watchdog needs to monitor subprocess output, it may be interesting to use popen().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.