我不是 C 方面的专家,我正在寻找一些建议来使我的程序更加健壮和可靠。只是为了提供一些背景信息:我编写了一个程序来执行一些科学计算,该程序需要相当长的时间(大约 20 小时),我正在使用 SLRUM 调度系统和 NFS 安装的文件系统在大型大学 HPC Linux 集群上执行。似乎发生的情况是,在 20 小时内的某个时间,与文件系统的连接变得陈旧(在整个计算机上;独立于我的程序),并且第一次尝试打开和写入文件需要很长时间,这会导致segfault cored dumped 错误,到目前为止我还无法精确追踪。下面是一个最小文件,至少在概念上重现了该错误:程序启动,打开一个文件,一切正常。该程序进行了一些长时间的计算(由 sleep() 模拟),尝试再次打开并写入同一文件,但失败了。有哪些约定可以使我的代码更加健壮并可靠地将结果写入文件而不会崩溃?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv) {
// Declare variables
FILE *outfile;
char outname[150] = "result.csv";
// Open file for writing
printf("CHECKING if output file '%s' is writable?", outname);
outfile=fopen(outname, "w");
if (outfile == NULL) {
perror("Failed: ");
exit(EXIT_FAILURE);
}
fclose(outfile);
printf(" PASSED.\n");
// Do some computation that takes really long (around 19h)
sleep(3);
// Open file again and Write results
printf("Writing results to %s ...", outname);
outfile=fopen(outname, "w");
if (outfile == NULL) {
perror("Failed writing in tabulate_vector_new: ");
exit(EXIT_FAILURE);
}
fprintf( outfile, "This is the important result.\n");
fclose(outfile);
printf(" DONE.\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
由于 NFS 问题,您的程序会出现段错误,这似乎很奇怪。我希望它会无限期地挂起,而不是崩溃。话虽如此,我建议分叉一个新进程来检查 NFS 挂载是否正常工作。这样,您的重要代码就不会直接参与测试有问题的文件系统。像下面这样的方法可能会有用:
pid_t pid = fork();
if (pid == -1)
{
// error, failed to fork(). should probably give up now. something is really wrong.
}
else if (pid > 0)
{
// if the child exits, it has successfully interacted with the NFS file system
wait(NULL);
// proceed with attempting to write important data
}
else
{
// we are the child; fork df in order to test the NFS file system
execlp("df", "df", "/mnt", (char *)NULL)
// the child has been replaced by df, which will try to statfs(2) /mnt for us
}
Run Code Online (Sandbox Code Playgroud)
这里的一般概念是我们利用该df命令来检查 NFS 文件系统(我假设位于/mnt)是否正在工作。如果它暂时不工作,df应该挂起直到它再次开始工作,然后退出,将控制权返回给您的程序。如果您怀疑df可能会永远挂起,您可以通过alarm(2)等待一段时间(可能至少几分钟)来增强我的示例,然后您可以重试运行df。请注意,这可能会导致僵尸df进程持续存在。
最后,正确的解决方案是尝试获得更可靠的 NFS 服务器,但在您能够做到这一点之前,我希望这会有所帮助。