【问题标题】:How to use execvp or any of the other exec's to run on only one file?如何使用 execvp 或任何其他 exec 仅在一个文件上运行?
【发布时间】:2021-12-14 21:35:24
【问题描述】:

我想执行 execvp,或者实际上任何可以为此工作的,但只在给定的文件上运行它。为了解释我想要做什么,我试图在满足给定其他参数的文件上运行它。例如: (./a.out -s 1024 -e "ls -l") -s 如果文件大小 >= 1024,则显示该文件,然后对该文件执行命令“ls -l”。我的代码检查目录中的每个文件,只显示通过的文件。我无法理解如何只显示一个文件而不是目录中的所有文件。

if (flagArgs.e_flag) // e case
{
    char *cmd = "ls";
    char *argv[3];
    argv[0] = "ls";
    argv[1] = "-la";
    argv[2] = NULL;
    printf("DIRFILE: %s\n", dirfile);

    if (strcmp(line, "") != 0){
        if ((pid = fork()) < 0) {     /* fork a child process           */
            printf("*** ERROR: forking child process failed\n");
            exit(1);
        }
        else if (pid == 0) {          /* for the child process:         */
            if (execvp(dirfile, argv) < 0) {     /* execute the command  */
                printf("*** ERROR: exec failed\n");
                exit(1);
            }
        }
        else {                                  /* for the parent:      */
            while (wait(&status) != pid)       /* wait for completion  */
                ;
        }
    }

}

我知道我在这段代码中使用了错误的 execvp,因为我应该传递 (cmd, argv) 但我试图弄清楚如何在一个单一文件上运行给定的命令。有什么办法我可以做到这一点或使用 execvp 错误?

感谢您的帮助!

【问题讨论】:

    标签: c file fork execvp


    【解决方案1】:

    将文件名添加到argv 数组。 execvp() 的第一个参数应该是要运行的程序,通常与argv[0] 相同。

    if (flagArgs.e_flag) // e case
    {
        char *cmd = "ls";
        char *argv[4];
        argv[0] = "ls";
        argv[1] = "-la";
        argv[2] = dirfile;
        argv[3] = NULL;
        printf("DIRFILE: %s\n", dirfile);
    
        if (strcmp(line, "") != 0){
            if ((pid = fork()) < 0) {     /* fork a child process           */
                printf("*** ERROR: forking child process failed\n");
                exit(1);
            }
            else if (pid == 0) {          /* for the child process:         */
                if (execvp(argv[0], argv) < 0) {     /* execute the command  */
                    printf("*** ERROR: exec failed\n");
                    exit(1);
                }
            }
            else {                                  /* for the parent:      */
                while (wait(&status) != pid)       /* wait for completion  */
                    ;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-26
      • 2011-06-30
      • 1970-01-01
      • 2020-12-18
      • 2012-03-31
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      • 2015-12-14
      相关资源
      最近更新 更多