Ubuntu-Daemon does not create file

206 Views Asked by At

I'm trying to run a simple daemon on Ubuntu 18.04.2 LTS, which should write some data into a log file. The parent process terminates with exit code 0, but no file is created.

Furthermore, when I set a breakpoint after fork(), pid is 835 for example. When I query the process name of this program with ps -p 835 -o comm=, I get LinuxTest.out <defunct>, but when I let the program continue and query the process name again, no output is shown, even though the child process should be still running due to the infinite loop later in the code.

I am using Visual Studio 2019 with Remote Build. I have also tried to log in per SSH into the server and execute the built program there with sudo rights, but nothing happened too.

int main() {
    pid_t pid, sid;

    // Fork off the parent process
    pid = fork();

    // if we got a good PID, then we can exit the parent process
    if(pid > 0) exit(EXIT_SUCCESS);
    else exit(EXIT_FAILURE);


    // create new SID for child process
    sid = setsid();
    if(sid < 0) exit(EXIT_FAILURE);

    // change the current working directory
    if(chdir("/") < 0) {
        exit(EXIT_FAILURE);
    }

    // change the file mode mask
    umask(0);

    // close out the  standard file descriptors
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    // Open a log file in write mode.
    FILE* fp = fopen("Log.txt", "w+");
    while(1) {
        sleep(1);
        fprintf(fp, "Logging info...\n");
        fflush(fp);
    }
    fclose(fp);
}

Why is the point to create the file not reached and why doesn't stay the child process alive?

1

There are 1 best solutions below

0
On BEST ANSWER

You have:

if(pid > 0) exit(EXIT_SUCCESS);
else exit(EXIT_FAILURE);

When formatted in a more orthodox style, that is the same as:

if (pid > 0)
    exit(EXIT_SUCCESS);
else
    exit(EXIT_FAILURE);

If the fork() succeeds, the parent exits successfully and the child exits with a failure status; if the fork() fails, the parent exits with a failure status.

Change that to:

if (pid > 0)
    exit(EXIT_SUCCESS);
else if (pid < 0)
    exit(EXIT_FAILURE);

/* Child is running here: pid == 0 */