我有一个程序可以检查文件的修改时间并在文件发生更改时执行该文件。目前,如果我在 mac 上运行它,它可以工作,但如果我在 ubuntu 上运行它,它会出现段错误。请帮助我。
注意:这是在c中
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define CONTERROR(cond, statement) \
if (cond) { \
perror(statement); \
continue; \
}
#define FATALERROR(cond, statement) \
if (cond) { \
perror(statement); \
exit(EXIT_FAILURE); \
}
/**
* Handler for the signals.
*/
static void handler(int signum) {
;
}
/**
* Main.
*/
int main(int argc, char *argv[]) {
struct sigaction sa;
struct stat buf;
struct itimerval tb;
pid_t pid;
int modTime;
if (argc != 2) {
fprintf(stderr, "usage: remote file\n");
exit(EXIT_FAILURE);
}
FATALERROR(stat(argv[1], &buf) == -1, "stat");
modTime = buf.st_mtime;
tb.it_interval.tv_sec = 0;
tb.it_interval.tv_usec = 50000;
tb.it_value.tv_sec = 0;
tb.it_value.tv_usec = 50000;
setitimer(ITIMER_REAL, &tb, 0);
sa.sa_handler = handler;
FATALERROR(sigemptyset(&sa.sa_mask) == -1, "mask");
FATALERROR(sigaction(SIGALRM, &sa, NULL) == -1, "sigaction");
while (1) {
pause();
CONTERROR(stat(argv[1], &buf) == -1, "stat");
if (modTime != buf.st_mtime) {
modTime = buf.st_mtime;
pid = fork();
FATALERROR(pid == -1, "fork");
if (!pid) {
execlp("rexec", "rexec", NULL);
fprintf(stderr, "exec\n");
}
}
}
exit(EXIT_SUCCESS);
}
最佳答案
大部分 sigaction 结构未初始化,因此可能包含随机数据。如果 sa_flags.SA_SIGINFO 被意外设置在这个未初始化的数据中,那么该信号将导致 sa_sigaction 而不是 sa_handler 被调用,而 sa_handler 也是未初始化的,因此几乎肯定会崩溃。
如果初始化所有字段,包括确保设置标志以确保信号按照您想要的方式运行,您可能会发现调试起来会更容易。
关于c - 为什么我在 Ubuntu 上遇到段错误,但在 Mac 上却没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5495921/