int bytes_read;
int rv;
int nchars = 200; /*max possible number for the input of the user*/
size_t nbytes = nchars; /*size of chars in bytes*/
char *commands[2];
char *line = malloc(nbytes + 1);
bytes_read = getline(&line, &nbytes, stdin); /*read line from stdin*/
if (bytes_read == -1) {
printf("Read line error");
exit(-1);
} else {
if (line[strlen(line-1)] == '\n') {
line[strlen(line-1)] = '\0'; /*change new line character in the end of the line of stdin*/
}
}
if (strcmp(line,"exit") == 0) {
rv = 3;
exit(rv);
}
commands[0] = line;
commands[1] = NULL;
execvp(commands[0], commands);
perror("Execution error");
exit(-1);
上記のコードに問題があります。ターミナルからユーザーからの入力を取得するために使用するgetline
か、または入力する場合、たとえばexecvpと入力すると、「そのようなファイルまたはディレクトリはありません」と出力されます。しかし、私が置くと、それは正しく実行されます。理由は何でしょうか?fgets
"ls"
commands[0]="ls"