%20.png)
Ich habe meine eigene Shell in Linux erstellt. Sie nimmt Dateipfade und Befehle an. Sie führt einfache Befehle wie grep ls usw. aus. Sie verwendet den Systemaufruf execlp().
zB /bin/ls ls < dieser Befehl wird ordnungsgemäß ausgeführt.
ls < dieser Befehl wird nicht ausgeführt!
Ich möchte nur wissen, was ich hier falsch mache?
#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
}
Antwort1
Das Problem besteht darin, dass Ihnen ein Parameter fehlt execlp
. Sie müssen den auszuführenden Befehl und dann alle seine Argumente angeben, einschließlich des ersten Arguments, das der Name des Befehls ist:
execlp(parsed[0], parsed[0], parsed[1], parsed[2], parsed[3], parsed[4], (char*) NULL);
Der erste parsed[0]
wird als Parameter übernommen execlp
und path
der zweite ist der erste , der im ausgeführten Befehl arg
endet .argv[0]