32.0k views
1 vote
Before your shell forks a new process to call execvp(), it should parse the input string and separate it into a collection of substrings representing the executable file and any command-line arguments. If the user entered an empty line, report an error and fetch a new line of input. Your code must handle at least four command-line arguments (in addition to the name of the executable file itself).

1 Answer

4 votes

Answer:

#define LSH_RL_BUFSIZE 1024

char *lsh_read_line(void)

{

int bufsize = LSH_RL_BUFSIZE;

int position = 0;

char buffer = malloc(sizeof(char) bufsize);

int c;

if (!buffer) {

fprintf(stderr, "lsh: allocation error\\");

exit(EXIT_FAILURE);

}

while (1) {

// Read a character

c = getchar();

// If we hit EOF, replace it with a null character and return.

if (c == EOF || c == '\\') {

buffer[position] = '\0';

return buffer;

} else {

buffer[position] = c;

}

position++;

// If we have exceeded the buffer, reallocate.

if (position >= bufsize) {

bufsize += LSH_RL_BUFSIZE;

buffer = realloc(buffer, bufsize);

if (!buffer) {

fprintf(stderr, "lsh: allocation error\\");

exit(EXIT_FAILURE);

}

}

}

}

Step-by-step explanation:

User John Deer
by
8.2k points