系統呼叫 Execlp()

系統呼叫 Execlp()

我在 Linux 中建立了自己的 shell。它運行簡單的命令,如 grep ls 等。

例如 /bin/ls ls < 該指令可以正確執行。

ls < 該指令不執行!

我只是想知道我在這裡做錯了什麼?

#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <cstring>
#include <sys/types.h>
using namespace std;

int main (int argc, char * argv[])
{
    while (true){
    char * input;
    string insert;
    char * token;
    char * parsed[5];
    int count=0;

    cout<<"My Shell $";
    getline(cin,insert);
    input= new char [insert.size()+1];
    strcpy(input, insert.c_str());

    for (int i=0; i<5; i++)
        parsed[i]=NULL;

    token=strtok(input, " ");
    while (token!=NULL)
    {
        parsed[count] = new char[strlen(token) + 1];
        strcpy(parsed[count++],token);
        token=strtok(NULL, " ");
    }
    delete input;
    delete token;


    pid_t mypid=fork();


    if (mypid==0)
    {

            execlp (parsed[0],parsed[1],parsed[2],parsed[3],parsed[4], (char*) NULL); 

    }
    else if (mypid>0)
    {
        wait(NULL);
    }

    } //end of while
}

答案1

問題是你缺少一個參數execlp;您需要指定要執行的命令,然後指定其所有參數,包括第一個參數,即命令的名稱:

execlp(parsed[0], parsed[0], parsed[1], parsed[2], parsed[3], parsed[4], (char*) NULL);

第一個parsed[0]作為execlppath參數,第二個作為第一個arg,最終出現argv[0]在執行的命令中。

相關內容