Question

In: Computer Science

I am trying to create a basic shell program in C that runs 10 commands and...

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;
}

Solutions

Expert Solution

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;
}


Related Solutions

I am trying to create a makefile for the following program in Unix. The C++ program...
I am trying to create a makefile for the following program in Unix. The C++ program I am trying to run is presented here. I was wondering if you could help me create a makefile for the following C++ file in Unix and show screenshots of the process? I am doing this all in blue on putty and not in Ubuntu, so i don't have the luxury of viewing the files on my computer, or I don't know how to...
I am trying to create a program That works with two other programs in c++ and...
I am trying to create a program That works with two other programs in c++ and a makefile. Only Shape.cpp can be modified. and it needs to work on a unix machine. It isn't running on my machine. And gives me an error message that it doesn't recomize cin and endl The program will accept a character and an X and Y coordinate. Dependign on the Charactor, It will then tell you what Cells that shape occupies. I almost have...
I am writing a shell program in C++, to run this program I would run it...
I am writing a shell program in C++, to run this program I would run it in terminal like the following: ./a.out "command1" "command2" using the execv function how to execute command 1 and 2 if they are stored in argv[1] and argv[2] of the main function?
I am trying to create a program that reads from a csv file and finds the...
I am trying to create a program that reads from a csv file and finds the sum of total volume in liters of liquor sold from the csv file by county and print that list out by county in descending order. Currently my program runs and gives me the right answers but it is not in descending order. I tried this:     for county, volume in sorted(sums_by_volume.items(), key=lambda x: x[1], reverse=True):         index +=1         print("{}. {} {:.2f}".format(county, sums_by_volume[county]))      When I run...
Create shell in C which meets requirements below: 1. The shell must support the following internal commands:
Create shell in C which meets the requirements below:1. The shell must support the following internal commands:i.cd - Change the current default directory toIf the argument is not present, report the current directory. If the directory does not exist an appropriate errorshould be reported. This command should also change thePWD environment variable.ii. clr - Clear the screen.iii. dir - List the contents of directory. iv.environ - List all the environment strings.v. echo - Display on the display followed by a newline...
Hello, I am trying to write a C++ program that will do the following: Use the...
Hello, I am trying to write a C++ program that will do the following: Use the STL stack container in a program that reads a string, an arithmetic expression to be exact, one character at a time, and determines if the string has balanced parenthesis – that is, for each left parenthesis there is exactly one matching right parenthesis later in the string.                         Use the following strings to test your program. A+ B - C A * B / (C...
I am having a trouble with a python program. I am to create a program that...
I am having a trouble with a python program. I am to create a program that calculates the estimated hours and mintutes. Here is my code. #!/usr/bin/env python3 #Arrival Date/Time Estimator # # from datetime import datetime import locale mph = 0 miles = 0 def get_departure_time():     while True:         date_str = input("Estimated time of departure (HH:MM AM/PM): ")         try:             depart_time = datetime.strptime(date_str, "%H:%M %p")         except ValueError:             print("Invalid date format. Try again.")             continue        ...
I am trying to write code for a program in Visual Studo using Visual Basic programming...
I am trying to write code for a program in Visual Studo using Visual Basic programming language that computes the factorial of an entered number by using a For Loop. My problem is that it keeps re-setting the variable for Factorial. Below is my code if anyone can help. I want it to multiply the given number by that number - 1, then continuing to do so until it hits zero without multiplying by zero. Private Sub BtnCalculate_Click(sender As Object,...
Hi I am having the following problem. At the moment I am trying to create a...
Hi I am having the following problem. At the moment I am trying to create a bode plot for the following function. G(s)=(Ks+3)/((s+2)(s+3)) Note: Not K(s+2)! I then want to plot multiple bode plots for various values of K. Eg. 1,2,3, etc. I am having two separate issues. 1. How do I define the TF with a constant K in the location required (a multiple of s in the numerator) 2. How do I create multiple bode plots for values...
I am trying to create a classified balance sheet and I am unsure what is involved...
I am trying to create a classified balance sheet and I am unsure what is involved when reporting the current assets, liabilities and owners equity?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT