我有一个简单的功能 - 它的目的是在覆盖之前将文件复制到 .old 。因为我很懒(这里的答案建议这样做),所以我分叉并使用 cp 来完成这项工作。
然后我调用 waitpid 并检查返回码。
调用它的代码调用我的复制函数,然后立即打开文件进行读取。不知何故,调用代码似乎在 cp 调用之前运行 - 新文件是被复制的。最好的例子是文件和备份都不存在。两者都是创建并包含我的保存调用输出的内容。
我正在努力查看我哪里出错了,我们将不胜感激。
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");
}
}
}