C - exec() 位于另一个目录中的文件

标签 c linux unix exec

<分区>

如何使用 exec() 函数之一执行位于另一个目录中的二进制文件(从 c 源代码编译)? 我正在使用 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);
}

最佳答案

您的一个问题是:

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

你正在践踏数组的边界。实际上,在标准 C 中,根本不能有 0 维数组。对(不存在的)args[1] 的赋值很有可能会损坏或覆盖指针 event(尽管您可能期望核心转储而不仅仅是一个'execvp() 失败'消息)。你需要:

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

不要忘记在 execvp() 失败后执行 exit(),否则您将有两个进程读取数据,这会变得非常困惑。您还应该报告有关“stderr”的错误;它是报告错误的标准流。

关于C - exec() 位于另一个目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16026052/

相关文章:

c - 使用预处理器定义的可选查找表

linux - 在 UNIX 中将一个文件的内容附加到另一个文件的开头

unix - 调整大小/Dev/SDA1 : Google Cloud

调用 free() 时崩溃

linux - Linux 命令行上多个文件的总和列

unix - Grep 多个字符串,然后替换文本

linux - 重写一个脚本,让它接受选项参数来控制它的行为

c - 调试多线程程序的技巧

c - 如何在 C 中连接常量/文字字符串?

打开文件时出现 C 段错误