2011-03-31 107 views
0

我有一个程序检查文件的修改时间,并在文件发生更改时执行该文件。目前它工作,如果我在我的Mac上运行它,但它seg故障,如果我在Ubuntu上运行它。请帮帮我。为什么我在Ubuntu上遇到seg故障而不是mac?

注:这是在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); 
} 
+1

你有没有试过用gdb运行它?它在哪里崩溃? – DarkDust 2011-03-31 06:15:29

+0

我在Linux上试过它(Ubuntu 9.4)。什么都没发生。您作为参数传入的文件的权限是什么? – 2011-03-31 06:23:01

+0

它可能是一个是32位而另一个是64位操作系统的问题? – SlappyTheFish 2011-03-31 06:59:32

回答

1

你的大部分sigaction的结构没有初始化,所以可能包含随机数据。如果sa_flags.SA_SIGINFO被意外设置在这个未初始化的数据中,那么该信号将导致sa_sigaction而不是sa_handler被调用,这也是未初始化的,所以几乎肯定会崩溃。

如果初始化所有字段,包括确保以某种方式设置标志以确保信号的行为符合您的要求,您可能会发现调试更容易。