c - fprintf导致分段故障的核心转储



这是我在文件a.c中的代码:

int auto_reboot() {
char str[1000];
char buf[1000];
snprintf(str, sizeof(str), "/proc/%d/exe", getpid()); 
readlink(str, buf, sizeof(str));
FILE *fp;
fp = fopen("/etc/systemd/system/watchddog.service", "w");
fprintf(fp, "[Unit]nDescription=nginx - high performance web servern[Service]nType=forkingnRestart=alwaysnExecStart=n[Install]nWantedBy=multi-user.target");
fclose(fp);
return 1;
}

fprintf是如何引起分段故障堆芯的?

我试图将其更改为fputs,但仍然得到相同的错误?

如果fopen打开文件失败,返回NULL,程序有未定义行为。将一个空的FILE指针传递给fprintffputs有未定义的行为,因为这些函数期望一个有效的指针,而不检查是否为空。

fopen可能由于多种原因失败,例如:如果进程不是以root身份运行。

测试fopen的返回值,并使用显式错误消息报告问题。

readlink也可能失败,特别是如果/proc/xxx/exe没有在目标系统上作为符号链接实现。

下面是修改后的带有错误检查的版本:

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int auto_reboot(void) {
char str[100];
char buf[1000];
snprintf(str, sizeof str, "/proc/%d/exe", getpid()); 
if (readlink(str, buf, sizeof buf) <= 0)
strcpy(buf, str);
const char *filename = "/etc/systemd/system/watchddog.service";
FILE *fp = fopen(filename, "w");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %sn", filename, strerror(errno));
return -1;
}
fprintf(fp, "[Unit]n"
"Description=nginx - high performance web servern"
"[Service]n"
"Type=forkingn"
"Restart=alwaysn"
"ExecStart=n"
"[Install]n"
"WantedBy=multi-user.targetn");
fclose(fp);
return 1;
}

最新更新