In: Computer Science
I am trying to create a basic shell program in C that runs 10 commands and then quits. Only one word commands are required, like:
cal, date, ls, ps, pwd, who, quit
The part I am struggling with is passing the scanned command into my array in the child process to be executed using execvp().
Here is my code:
#include <stdio.h>
#include <string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<readline/readline.h>
#include<readline/history.h>
#define MAX_CMD_NUMBER 10
int main()
{
   int i;
   char command[10];
   for (i=0; i< 10; i++)
    {
      printf("COMMAND-> ");
      fflush(stdout);
      scanf("%s", command); // takes in
the user's single-string command
      if (strcmp(command, "quit") ==
0)
         i =
MAX_CMD_NUMBER; // terminate the loop
      else
         printf("Command
#%d is: %s\n", i, command);
     }
printf("hello world (pid:%d)\n", (int) getpid());
int rc = fork();
    if (rc < 0) {
        // fork failed;
exit
        fprintf(stderr, "fork
failed\n");
        exit(1);
    }
    else if (rc == 0)
    {
        char *command[2];
        command[0] =
strdup(command);
        command[1] =
NULL;        
        execvp(command[0],
command);
        printf("this shouldn't
print out");
    }
      else
      {
        command =
wait(NULL);
    }
    return 0;
}
Looked like some lines were out of for loop. I have changed the code slightly to include lines in loop and passing arguments. Can you please check and let me know if it works for you now?
#include <stdio.h>
#include <string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#define MAX_CMD_NUMBER 10
int main()
{
int i;
char command[10];
for (i=0; i< 10; i++)
{
printf("COMMAND-> ");
fflush(stdout);
scanf("%s", command); // takes in the user's single-string
command
if (strcmp(command, "quit") == 0)
i = MAX_CMD_NUMBER; // terminate the loop
else
printf("Command #%d is: %s\n", i, command);
       printf("hello world (pid:%d)\n",
(int) getpid());
       int rc = fork();
       if (rc < 0) {
           // fork failed;
exit
           fprintf(stderr,
"fork failed\n");
           exit(1);
       }
       else if (rc == 0)
       {
           char
*args[2];
           args[0] =
strdup(command);
           args[1] =
NULL;
           execvp(args[0],
args);
           printf("this
shouldn't print out");
       }
       else
       {
       wait(NULL);
       }
   }
return 0;
}
