开发者

Why do I get a seg fault on Ubuntu but not mac?

I have a program that checks the modification time of a file and executes the file if it has changed. Currently it works if I run it on my mac, but it seg faults if I run it on ubuntu. Please help me.

note: this is in 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.t开发者_开发百科v_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);
}


Most of your sigaction structure is not initialized, so could contain random data. If sa_flags.SA_SIGINFO is accidentally set in this uninitialized data, then the signal will cause sa_sigaction instead of sa_handler to be called, which is also uninitialized, so will almost certainly crash.

You may find it easier to debug if you initialize all the fields, including making sure you have set the flags in a way the ensures the signals behaves the way you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜