簡體   English   中英

UNIX shell C執行管道

[英]UNIX shell C execution of pipe

我的程序應該從終端獲取輸入並執行命令,例如:“ls”或“ls -l | wc”

{...}

//Split the command and store each string in parameter[]
    parameter[0] = malloc(255);                     //Allocate some space to the first element in the array
    cp = strtok(command, " ");                      //Get the initial string (the command)
    strncpy(parameter[0], cp, 50);
    for(i = 1; i < MAX_ARG; i++)
    {
        parameter[i] = malloc(255);
        cp = strtok(NULL, " ");                 //Check for each string in the array
        parameter[i] = cp;                      //Store the result string in an indexed off array
        if(strcmp(parameter[i], "|") == 0)
        {
            i = MAX_ARG;
            cp = strtok(NULL, " ");
            parameter2[0] = malloc(255);
            strncpy(parameter2[0], cp, 50);
            break;
        }
        if(parameter[i]  == NULL)
        {
            break;
        }
    }

    //Find the second set of commands and parameter
    //strncpy(parameter2[0], cp, 50);
    for (j = 1; j < MAX_ARG; j++)
    {
        parameter2[j] = malloc(255);
        cp = strtok(NULL, " ");
        parameter2[j] = cp;
    }

{...} //這是命令和參數部分的執行:

if (proc1 ==  0)
        {
            close(fd[0]);                           //process1 doenst need to read from pipe
            close(STD_INPUT);                       //prepare for output
            dup(fd[1]);                             //Standard output = fd[1]
            close(fd[1]);
            execvp(parameter[0], parameter);        //Execute the process
        }


 else {
if (proc2 == 0)
            {
                close(fd[1]);
                close(STD_OUTPUT);
                dup(fd[0]);
                close(fd[0]);
                execvp(parameter2[0], parameter2);
            }
            //Parent process
            else
            {
            waitpid(-1, &status, 0);            //Wait for the child to be done
            }
   }

我不確定我做錯了什么,因為當我輸入“ls -l | wc”時,我收到一條消息“|在目錄中找不到”

你可以直接用execvp執行ls和wc,但是| 是shell程序的一個特性。 所以你真正需要做的是運行bash,然后作為參數傳遞你的命令

execl("/bin/bash","-c",command);

這是微不足道的,看起來你真正應該做的就是自己實現shell。 為此,您需要進行一些解析,而不僅僅是使用strtok進行天真的標記。 如果這是一個任務,我希望他們會給你明確的說明,或者至少你需要接受什么樣的shell命令(只是管道?子shell可能?)。 如果你只是想自己實現這個,我會先閱讀一些編譯工具,比如lex和yacc ,它們可以幫助你解析shell命令並執行它們。

暫無
暫無

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

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