0

如何使用 exec() 函数之一执行位于另一个目录中的二进制文件(从 ac 源代码编译)?我正在使用 inotify API,并且我想执行位于另一个目录中的文件。这是作业:在创建文件时通知;如果此文件是可执行文件,则执行它。

这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/inotify.h>
#include <sys/wait.h>

#define EVENT_SIZE      (sizeof(struct inotify_event))
#define EVENT_BUF_LEN   (1024 * (EVENT_SIZE + 16))

int main(int argc, char *argv[]) {

int fd, wd, length = 0;
char buffer[EVENT_BUF_LEN];
struct stat sb;

if(argc != 2) {
    printf("Usage: ./spy dirpath\n");
    exit(EXIT_FAILURE);
}

if( (fd = inotify_init()) == -1 )
    perror("inotify_init()");
if( (wd = inotify_add_watch(fd, argv[1], IN_CREATE)) == -1 )
    perror("inotify_add_watch");
while(1) {  
    if( (length = read(fd, buffer, EVENT_BUF_LEN)) < 0 )
        perror("read()");
    struct inotify_event *event = (struct inotify_event *)&buffer;
    if(event->len) {
        if(event->mask & IN_CREATE) {
            if(event->mask & IN_ISDIR)
                continue;
            else {
                if(access(event->name, X_OK)) {
                    printf("New executable file created\n");                
                    pid_t child;
                        int cstatus;
                        child = fork();
                        if(child > 0) { /* father */
                wait(&cstatus);
                }
    else { /* child */
        chdir(argv[1]);
        /* This time, I try to tell it directly the filename*/
        char *args[2] = { "./helloworld" ,NULL };
        execvp(args[0], args);
        printf("execvp failed\n");
                    exit(EXIT_FAILURE);
    }

            }
        }
    }
}

inotify_rm_watch(fd, wd);
close(fd);

return(0);
}
4

1 回答 1

1

您的问题之一是:

    char *args[0]; args[1] = NULL;

您正在践踏您的阵列范围。实际上,在标准 C 中,您根本不能拥有维度为 0 的数组。分配给(不存在的)args[1]损坏或覆盖指针event的可能性很大(尽管您可能期望核心转储而不仅仅是“execvp()失败”消息)。你需要:

    char *args[2] = { event->name, NULL };

exit()失败后不要忘记这样execvp()做,否则最终会导致两个进程读取数据,这会变得非常混乱。您还应该报告“stderr”上的错误;它是报告错误的标准流。

于 2013-04-15T23:25:19.787 回答