簡體   English   中英

文件操作。 將使用 fork() execvp() , wait/waitpid() 接受單個命令行參數的 c 程序

[英]File operations. A c program that will take a single command line argument using fork() execvp() , wait/waitpid()

我正在編寫一個可以在 c 程序中傳入命令行參數的程序。 linux 命令存儲在一個名為“sample-input”的文件中。 它只包含 cp file1 dest1 或 mv file2 dest2。 我的問題是當我標記文件中的字符串時。 它似乎只讀取文件的第一行。 這是我的代碼。 有人能幫助我嗎?

error message i got (after edit):

    temp1/f4.txt
 temp1/f5.txt
 temp1/f6.txt
-temp1/f7.c
+temp1/f8.c
+temp2/f1.txt
 temp2/f2.c
+temp2/f3.txt
 temp2/f4.txt
+temp2/f5.txt
 temp2/f6.txt
 temp2/f9.c
Test Result: [Failed]


    my sample-input
    cp temp1/f1.txt              temp2/
    mv temp1/f2.c                           temp2/
    cp temp1/f3.txt                temp2/
    cp temp1/f4.txt                temp2/
    cp temp1/f5.txt                temp2/
    cp temp1/f6.txt                 temp2/
    mv temp1/f7.c                   temp1/f8.c
    mv temp1/f9.c                   temp2/
    cp temp1/f1.txt              temp1/f1a.txt

我當前的代碼。

   /* Your code goes here */

#define _GNU_SOURCE
#include <string.h>
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


int main(int argc, char* argv[])
{
    FILE* fp;
    fp = fopen("sample-input", "r");

    if (fp == NULL) {
        fprintf(stderr, "An error has occured1\n");
        exit(1);
    }
    if (argc != 2) {
        fprintf(stderr, "argc=%d\n", argc);
        fprintf(stderr, "An error has occured2 \n");
        exit(1);
    }
    else if (argc == 2) {
        char ag[1024];

        while (fgets(ag, 1024, fp) != NULL)
        {
            fgets(ag, 1024, fp);

            char* array[4];
            int i = 0;
            char* token = strtok(ag, " \t\n");

            while (token != NULL) {

                array[i] = token;
                i++;
                token = strtok(NULL, " \t\n");
            }
            array[i] = NULL;
            int r = fork();

            if (r == 0) {
                execvp(array[0], array);
            }
            else if (r < 0) {

                fprintf(stderr, "An error an occoured\n");
                exit(1);

            }
            else {

                wait(NULL);

            }


        }




    }
    return 0;
}

這個

execvp(array[i], array);

必須

execvp(array[0], array);

因為第一個參數應該是可執行文件的文件名。 並且您應該通過發出消息並退出 (!) 來正確處理execvp()失敗的情況。

perror("execvp");
exit(EXIT_FAILURE);

此外,您必須通過設置以 NULL 終止參數向量

array[i] = NULL;

在你的 while 循環之后。 最好添加一個檢查,在解析三個參數后跳出循環,否則array可能溢出(寫出邊界導致未定義的行為)。

另一個問題是你的閱讀循環

while (fgets(ag, 1024, fp) != NULL) {
        fgets(ag, 1024, fp);
}

這會在某種程度上瘋狂地讀取您的文件,並為您留下最后一行或上一行。 您必須將線處理放在循環中:

while (fgets(ag, 1024, fp) != NULL) {
    // Parse arguments and fork/exec here inside
}

根據您的輸入文件,看起來制表符也可能是參數分隔符,因此請使用

strtok(ag, " \t\n");

strtok(NULL, " \t\n");

暫無
暫無

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

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