Se un utente digita "ls" execvp visualizza il risultato di "ls" sullo schermo. Vorrei archiviarlo in un array di caratteri come stringa. Qualcuno può aiutarmi? Grazie in anticipo.
int main () {
char response[1000];
char *buffer[100];
int pid, status;
printf("Please enter the shell command: ");
scanf("%s",&response);
pid = fork();
if (pid < 0) {
printf("Unable to create child process, exiting.n");
exit(0);
}
if (pid == 0) {
printf("I"m the child.n");
*buffer = response;
execvp(*buffer,buffer);
printf("execvp failedn");
}
else{
wait(&status);
exit(0);
}
}
risposte:
2 per risposta № 1popen()
è più appropriato per il tuo scopo di execvp()
poiché si desidera leggere l'output dal comando exec "(vedere il manuale collegato per un esempio).
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
popen()
ritorna FILE *
utilizzando il quale è possibile leggere l'output restituito dal comando.