Frage

Es liest Sachen von Kommandozeilen

Ich schreibe ein Mini-Shell besser vertraut mit Unix-Prozess-Management in C zu erhalten und übergibt diese Argumente über execlp an dem System.

# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>

#define MAXSIZE 100

char prompt[MAXSIZE];

int main(void)
{
   pid_t pid;

   printf("> ");

   // read stuff 
   if (fgets(prompt, MAXSIZE, stdin) == NULL){
      printf("Input validation error!");
      abort();
   }
   // printf("DEBUG: %s" , prompt);

   if (strcmp(prompt, "exit")==0) abort();


   if ((pid=fork())<0){       // copy process

      printf("Process error!");
      abort();
   }

   if (pid==0){                // exec in son-prcess

      char *command=(char*)strtok(prompt, " ");
      execlp(command, command, 0);  // overwrite memory

      printf("Error, command not found!");
      abort();
   } else {

      waitpid(pid, 0, 0);
    }
}

In der Tat dies wäre es, aber ich bekomme keine Ausgabe von execlp(). Weiß jemand, warum das so ist?

War es hilfreich?

Lösung

Ich habe versucht, das Programm läuft und es ist fehlgeschlagen, weil command eine \n (Newline) enthalten ist. Ich änderte es von \n statt „“ in den strtok setzen und es lief dann erfolgreich.

Im Detail:

  if (pid==0){                // exec in son-prcess
      char *command=(char*)strtok(prompt, "\n");
      printf ("'%s'\n", command);
      execlp (command, command, 0);  // overwrite memory
      printf("Error %d (%s)\n", errno, strerror (errno));
      abort();
   } else {

Testlauf:

$ ./a.out 
> ls
'ls'
(usual ls behaviour)

Andere Tipps

Kinopiko bereits gefunden, warum es nicht funktioniert, aber der Grund, warum Sie keine Fehlermeldung angezeigt haben, ist, dass Ihre Shell-Prompt es überschrieben wird. Versuchen Sie eine neue Zeile am Ende setzen:

printf("Error, command not found!\n");
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top