Open background application in C - Linux

2

I'm 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 '&' (required to open background process) as an expected parameter for the application.

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

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

    
asked by anonymous 05.08.2015 / 00:21

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 consists of performing the fork of the process and then changing the execution session of it, so that the parent process can be terminated without the child process being terminated. Thus, the child process becomes orphaned. It is equivalent to the operation 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 chdir("/"); command changes the working directory of the process. You can use another directory. In my case, I left "/" because the process executes in a chroot environment.

    
05.08.2015 / 03:17