簡體   English   中英

如何使用 execvp 或任何其他 exec 僅在一個文件上運行?

[英]How to use execvp or any of the other exec's to run on only one file?

我想執行 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 是錯誤的嗎?

謝謝你的幫助!

將文件名添加到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  */
                ;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM