Question

I have a simple function - its purpose is to copy a file to a .old before overwriting it. Because i'm lazy (and an answer on here suggested it) I fork and use cp to do the work.

Then i call waitpid and check the return codes.

The code calling this calls my copy function, then immediately opens the file for reading. Somehow the calling code seems to run before the cp call - the new file is what gets copied. The best example is if neither file nor backup exist. Both are created and contain what my save call outputs.

I am struggling to see where I have gone wrong, help would be appreciated.

copy_old();
std::ofstream savefile (SETTINGS_LOCATION);
if (savefile.is_open())
{
    savefile << ...


void settings::copy_old()
{
    int childExitStatus;
    pid_t pid;

    pid = fork();

    if (pid == 0) { /* child */
        execl("/bin/cp", "/bin/cp", "-f", SETTINGS_LOCATION, SETTINGS_LOCATION_B, (char *)0);
    }
    else if (pid < 0) {
        ERR("Could not Backup Previous Settings");
    }
    else {
        pid_t ws = waitpid( pid, &childExitStatus, WNOHANG);
        if (ws == -1)
        {
            ERR("Could not Backup Previous Settings1");
        }

        if( !WIFEXITED(childExitStatus) || WEXITSTATUS(childExitStatus)) /* exit code in childExitStatus */
        {
            ERR("Settings backup may have been unsuccessful");
        }
    }
}
Was it helpful?

Solution

Of course waitpid isn't waiting. You told it not to:

pid_t ws = waitpid( pid, &childExitStatus, WNOHANG);

WNOHANG means "don't wait". Change that WNOHANG to 0 if you want waitpid to wait.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top