Writing a Unix Shell - Part II - Why ?
by Victor43 from LinuxQuestions.org on (#5MSDC)
Hello all. I was reading the blog on writing a UNIX shell as seen here. The author of the article states the following:
"If you try to execute the cd command, you will get an error that says:
cd: No such file or directory" AND "The current working directory of the parent has not changed, since the command was executed in the child."
Here is the code for the above comments made by the author. So my question is why does the command not work when executed in the child process ?
Code:#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <readline/readline.h>
#include <unistd.h>
#include <sys/wait.h>
char **get_input(char *);
int main() {
char **command;
char *input;
pid_t child_pid;
int stat_loc;
while (1) {
input = readline("unixsh> ");
command = get_input(input);
if (!command[0]) { /* Handle empty commands */
free(input);
free(command);
continue;
}
child_pid = fork();
if (child_pid == 0) {
/* Never returns if the call is successful */
execvp(command[0], command);
printf("This won't be printed if execvp is successul\n");
} else {
waitpid(child_pid, &stat_loc, WUNTRACED);
}
free(input);
free(command);
}
return 0;
}
char **get_input(char *input) {
char **command = malloc(8 * sizeof(char *));
char *separator = " ";
char *parsed;
int index = 0;
parsed = strtok(input, separator);
while (parsed != NULL) {
command[index] = parsed;
index++;
parsed = strtok(NULL, separator);
}
command[index] = NULL;
return command;
}
"If you try to execute the cd command, you will get an error that says:
cd: No such file or directory" AND "The current working directory of the parent has not changed, since the command was executed in the child."
Here is the code for the above comments made by the author. So my question is why does the command not work when executed in the child process ?
Code:#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <readline/readline.h>
#include <unistd.h>
#include <sys/wait.h>
char **get_input(char *);
int main() {
char **command;
char *input;
pid_t child_pid;
int stat_loc;
while (1) {
input = readline("unixsh> ");
command = get_input(input);
if (!command[0]) { /* Handle empty commands */
free(input);
free(command);
continue;
}
child_pid = fork();
if (child_pid == 0) {
/* Never returns if the call is successful */
execvp(command[0], command);
printf("This won't be printed if execvp is successul\n");
} else {
waitpid(child_pid, &stat_loc, WUNTRACED);
}
free(input);
free(command);
}
return 0;
}
char **get_input(char *input) {
char **command = malloc(8 * sizeof(char *));
char *separator = " ";
char *parsed;
int index = 0;
parsed = strtok(input, separator);
while (parsed != NULL) {
command[index] = parsed;
index++;
parsed = strtok(NULL, separator);
}
command[index] = NULL;
return command;
}