I am trying to implement a shell that takes a command ; however, I can not get it to work properly. For example, if I type "ls -a", I get this:
invalid option -- '
'
Try 'ls --help' for more information.
I have probably made some bad mistakes as I am a beginner so please forgive me. Also, I will put the code that reads in the command into a function. Its just like this for testing- thanks.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <stddef.h>
int main()
{
pid_t pid;
int status;
char* token;
char* argv[20];
char input[100];
printf("AP> ");
while (1)
{
fgets(input, 100, stdin);
token = strtok(input, " ");
int i = 0;
//walk through other tokens
while (token != NULL) {
argv[i] = malloc(strlen(token) + 1);
strncpy(argv[i], token, strlen(token));
//argv[i] = token;
i++;
token = strtok(NULL, " ");
}
argv[i] = NULL; //argv ends with NULL
pid = fork();
if (pid < 0)
{
perror("fork error");
return EXIT_FAILURE;
}
else if (pid == 0)
{
// child process
execvp(argv[0], argv);
perror("execl error");
return EXIT_FAILURE;
}
else {
// parent process
if (waitpid(pid, &status, 0)<0)
{
perror("waitpid error");
return EXIT_FAILURE;
}
}
printf("AP> ");
}
return 0;
}
If you insert the following loop after the inner while loop, then you'll see that you aren't removing the newline character at the end of input before the while loop starts.
for (i=0; argv[i]; i++)
printf("argv[%d] = '%s'\n", i, argv[i]);
Alternatively, you can use:
" \n"
as your separators instead of just
" "
Related
So I am trying to read from standard input and then get the input ready so that later on it can be used inside execvp().
What I am implementing here is basically a pipe for some terminal commands.
Here is how an example of my code goes.
input:
ls -s1
sort -n
output:
commands[0]="ls"
commands[1]="-s1"
commands2[0]="��""
commands2[1]="��""
sort: cannot read: t: No such file or directory
Here is my code
# include <stdlib.h>
# include <stdio.h>
# include <unistd.h>
# include <string.h>
# include <sys/wait.h>
# define BUF_SIZE 256
int main()
{
char buffer[BUF_SIZE];
char *commands[5];
char *commands2[5];
int argc = 0;
int argc2 = 0;
fgets(buffer, BUF_SIZE, stdin);
for ( commands[argc] = strtok(buffer, " \t\n");
commands[argc] != NULL;
commands[++argc] = strtok(NULL, " \t\n") ) {
printf("commands[%d]=\"%s\"\n", argc, commands[argc]);
}
commands[argc] = NULL;
fgets(buffer, BUF_SIZE, stdin);
for ( commands2[argc2] = strtok(buffer, " \t\n");
commands2[argc2] != NULL;
commands2[++argc2] = strtok(NULL, " \t\n") ) {
printf("commands2[%d]=\"%s\"\n", argc2, commands2[argc]);
}
commands2[argc2] = NULL;
int my_pipe[2];
if (pipe(my_pipe) == -1)
{
perror("cannot create pipe\n");
}
pid_t my_pid;
my_pid = fork();
if (my_pid < 0)
{
perror("Failed fork\n");
}
if (my_pid > 0)
{
close(my_pipe[1]);
dup2(my_pipe[0], 0);
close(my_pipe[0]);
wait(NULL);
execvp(commands2[0],commands2);
}
else
{
close(my_pipe[0]);
dup2(my_pipe[1], 1);
close(my_pipe[1]);
execvp(commands[0],commands);
}
}
One major problem is that you read the second line over the first in buffer, and the commands[] array contains pointers into buffer too. That's not a recipe for happiness. The simplest fix is to define char buffer2[BUF_SIZE]; and use that in the second fgets() call and for loop.
Using argc in printf("commands2[%d]=\"%s\"\n", argc2, commands2[argc]); is a copy'n'paste bug — it should reference argc2 twice. This helped hide the previous problem.
Note that perror() does not exit; your code blunders on if pipe() fails, or if fork() fails.
The wait() in if (my_pid > 0) is bad; remove it.
If execvp() fails, you should report an error and exit with a non-zero status.
Putting those changes together yields code such as:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#define BUF_SIZE 256
int main(void)
{
char buffer[BUF_SIZE];
char buffer2[BUF_SIZE];
char *commands[5];
char *commands2[5];
int argc = 0;
int argc2 = 0;
fgets(buffer, BUF_SIZE, stdin);
for (commands[argc] = strtok(buffer, " \t\n");
commands[argc] != NULL;
commands[++argc] = strtok(NULL, " \t\n"))
{
printf("commands[%d]=\"%s\"\n", argc, commands[argc]);
}
commands[argc] = NULL;
fgets(buffer2, BUF_SIZE, stdin);
for (commands2[argc2] = strtok(buffer2, " \t\n");
commands2[argc2] != NULL;
commands2[++argc2] = strtok(NULL, " \t\n"))
{
printf("commands2[%d]=\"%s\"\n", argc2, commands2[argc2]);
}
commands2[argc2] = NULL;
int my_pipe[2];
if (pipe(my_pipe) == -1)
{
perror("cannot create pipe\n");
exit(EXIT_FAILURE);
}
pid_t my_pid = fork();
if (my_pid < 0)
{
perror("Failed fork\n");
exit(EXIT_FAILURE);
}
if (my_pid > 0)
{
close(my_pipe[1]);
dup2(my_pipe[0], 0);
close(my_pipe[0]);
execvp(commands2[0], commands2);
perror(commands2[0]);
exit(EXIT_FAILURE);
}
else
{
close(my_pipe[0]);
dup2(my_pipe[1], 1);
close(my_pipe[1]);
execvp(commands[0], commands);
perror(commands[0]);
exit(EXIT_FAILURE);
}
return EXIT_FAILURE;
}
When I run the program, it produces the appropriate output. Note that the return at the end of main() is actually never reached.
I am trying to make a some what shell in C but I am having problems with making the ls command. mkdir, and cd work fine but with ls it gives me
"Address out of bounds segmentation error"
Hope somebody can help me. Here's my code.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <readline/readline.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
printf("\033[1;33mWelcome To Crisp Bacon Shell\n");
while (1) {
printf("\033[0m%s $", hostname);
input = readline("");
command = get_input(input);
child_pid = fork();
if (child_pid < 0) {
perror("Fork failed");
exit(1);
}else 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;
}
The only thing I understand it has something to do with memory and references or pointers but I tried changing everything from & refrencing to pointers and it just gave me more errors what do I do?
There were many undeclared variables in your code snippets. You also need to fetch the hostname, it isn't a global variable. It's also a best practice to declare your functions before using them.
This works fine:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <readline/readline.h>
#include <unistd.h>
#include <sys/wait.h>
char **get_input(char *input) {
char **command = malloc(8 * sizeof(char *));
char *separator = " ";
int index = 0;
char *parsed = strtok(input, separator);
while (parsed != NULL && index < 8) { // you need to make sure the index does not overflow the array
command[index] = parsed;
index++;
parsed = strtok(NULL, separator);
}
command[index] = NULL;
return command;
}
int main() {
printf("\033[1;33mWelcome To Crisp Bacon Shell\n");
while (1) {
// hostname does not exist, you need to fetch it
char hostname[1024];
gethostname(hostname, 1023); // POSIX only
printf("\033[0m%s $", hostname);
char *input = readline(NULL);
char **command = get_input(input);
pid_t child_pid = fork();
if (child_pid < 0) {
perror("Fork failed");
exit(1);
} else 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, NULL, WUNTRACED); // since you don't use the middle argument, no need to point to valid data
}
free(input);
free(command);
}
return 0;
}
I'm trying to write a simple C shell. My problem is that I have written the program so that when the user enters a NULL value I've got the shell to exit and stop running. However after using different shells i've realised that the shell continues to loop. Is there anyway to fix this without having to rewrite my code? I'm still quite a novice to C.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#define MAX_CMD_SIZE 512
int getPath(){
printf("PATH = %s\n", getenv("PATH"));
return 0;
}
int setPath(char* arg){
setenv("PATH", arg, 1);
return 0;
}
int setwd() {
char *arg;
arg = getenv("HOME");
chdir(arg);
return 0;
}
int main()
{
char buff[MAX_CMD_SIZE]; //buff used to hold commands the user will type in
char *defaultPath = getenv("PATH");
char *args[50] = {NULL};
char *arg;
int i;
pid_t pid;
setwd();
while(1){
printf(">");
if (fgets(buff, MAX_CMD_SIZE, stdin) == NULL) { //Will exit if no value is typed on pressing enter
setPath(defaultPath);
getPath();
exit(0);
}
arg = strtok(buff, " <|>\n\t");
i = 0;
if (arg == NULL) return -1;
while (arg != NULL){
printf("%s\n", arg);
args[i] = arg;
arg = strtok(NULL, " <|>\n\t");
i++;
}
if (strcmp(args[0], "exit") == 0 && !feof(stdin)){ //Will exit if input is equal to "exit" or ctrl + d
setPath(defaultPath);
getPath();
exit(0);
}
else {
pid = fork();
if (pid < 0){ //Error checking
fprintf(stderr, "Fork Failed\n");
} else if (pid == 0){ //This is the child procsess
execvp(args[0], args);
exit(-1);
} else { //Parent Process
wait(NULL); // Parent will wait for child to complete
}
}
}
return 0;
}
I have an assignment requesting me to write a mini-shell - something that will get a command to execute, execute it, and wait for some more commands.
when I pass to this mini-shell the command ls . it prints the contest of the current directory. When I pass to it ls it prints nothing. Why?
here is my code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_CMD_SIZE 40
char** parse(char*);//will parse the arguments for the execv/excevp commands.
int main(int argc, char** argv)
{
bool debug = false;
assert(argc <= 2);
if (argc == 2)
{
//check for string -debug
debug = true;
}
if (debug)
printf("INFO: Father started PID[%d]\n", getpid());
char *command = malloc(MAX_CMD_SIZE);
while(true)
{
printf("minishell> ");
fgets(command, MAX_CMD_SIZE, stdin);
if (strcmp(command, "exit\n") == 0)
return 0;
pid_t pid = fork();
assert(pid >= 0);
if (pid == 0) //child
{
if (debug)
printf("INFO: Child started PID[%d]\n", getpid());
char** buf = parse(command);
if (debug)
{
int i;
for (i = 0; buf[i]; i++)
printf("INFO: buf[%d] = %s\n",i,buf[i]);
}
execvp(buf[0],buf);
return 0;
}
else //father
{
int status;
wait(&status);
if (debug)
printf("INFO: Child with PID[%d]terminated, continue waiting commands\n", pid);
}
}
}
char** parse(char *string)
{
char** ret = malloc(sizeof(char*));
ret[0] = strtok(string, " ");
int i = 0;
for (; ret[i]; ret[i] = strtok(NULL, " \n"))
{
ret = realloc(ret, sizeof(char*) * ++i);
}
return ret;
}
Your parse() command includes a \n in the last argument :)
So with a single ls, you're actually executing ls\n, which is not in the PATH (of course)
The problem is that on the first strtok() call, you only pass " " as a delimiter. Use " \n" (like in the subsequent calls) and the problem goes away.
You could also fix it by chomping the \n:
int l = strlen (string);
if (l > 0 && string [l - 1] == '\n') string [l - 1] = '\0';
and only using " " as a delimiter.
I wanna ask about how to make exec process programing by C.
Now, I typed like these code, and I use strtok and strdup.
my code wrong assign value from input, so could you see my code and could you teach what is wrong in the code.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
int main(){
int pid;
int status, i = 0;
char input[256], path[30];
const char* a[10];
char* token;
char* split = " ";
while(input != "exit"){
printf("Please type your command:\n");
fgets(input, 256, stdin); /* emxape: ls -alf argv[0] = "ls" argv[1] = -alf*/
printf("Input: %s", input);
i = 0;
token = strdup(strtok(input,split));
while(token != NULL){
a[i] = token;
token = strdup(strtok(NULL,split));
printf("a%d is %s\n", i, a[i]);
i++;
}
int j = 0;
while( j < sizeof(a))
{
printf("%s", a[j]);
j++;
}
//free(copy);
if(strcmp(a[0],"cd")== 0 )/*for compare pointer*/
{
if (chdir((a[1])) == 0) {
printf("Sucess change Directory.\n");
return 0;
}
else {
printf("Fault change Directroy\n");
perror("");
}
if (a[1] == NULL)
{
if(chdir(getenv("HOME"))<<0)
perror("cd");
return 0;
}
else
{
if(chdir(a[1]) <0)
perror("cd");
}
}
sprintf(path,"%s",a[0]);
pid = fork();
/*Child process*/
if(pid == 0){
//execl(path,a[0],a[1],NULL);
execl(a[0],a[1],a[2],NULL);
printf("Wrong child process: %s",path);
exit(0);
}
/*Parents Process*/
else {
wait(&status);
}
}//while
printf("Thank you.");
}/*main*/
There are at least 2 problems
Line 26: token = strdup(strtok(NULL,split)); should be token = strdup(strtok(input,split));
After the first modification, the loop in line 24 can run. but still does not run correctly. It seems the strtok(), and strdup() does not run correctly.