c - 为什么我在 Ubuntu 上遇到段错误,但在 Mac 上却没有?

标签 c macos ubuntu segmentation-fault

我有一个程序可以检查文件的修改时间并在文件发生更改时执行该文件。目前,如果我在 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/

相关文章:

swift - 如何从 Swift 4 中的字符串中提取未知子字符串?

macos - 如何使用brew安装llvm 5.0.0 for Mac

linux - 是否可以将 "push"消息发送到事件的 bash 终端?

java - 如何配置apache tomcat快速渲染页面

c++ - 通过 `gcc -v` 查看 Mac OS X 中 C header 的默认包含路径?

c - 在 C 中将 malloc 与结构体和指针一起使用

c - 由于需要结构/union ,microC 构建失败

c - 如何重置 c 中的链表?

java - Ubuntu : No Java SDK Found error 上的 IntelliJ

objective-c - 如何在 mac os View 或其 subview 获得焦点时处理事件?