Question

The original code using the gets() function is written below. You need to do (a) change...

The original code using the gets() function is written below. You need to do (a) change the provided code so that you now use fgets() function to obtain input from the user instead of gets(), (b) make any other necessary changes in the code because of using fgets() function, and (c) fill in the code for the execute() function so that the whole program works as expected (a simple shell program).

Note: part c is already done, and the execute function is already filled, just need to do part a and b.

CODE BELOW:

/* The program asks for UNIX commands to be typed and inputted to a string*/
/* The string is then "parsed" by locating blanks etc. */
/* Each command and corresponding arguments are put in a args array */
/* execvp is called to execute these commands in child process */

#include
#include
#include
#include
#include

void parse(char *buf, char **args);
void execute(char **args);
char *gets(char *s);

int main(int argc, char *argv[])
{
    char buf[1024];
    char *args[64];

    for (;;) {
        /*
         * Prompt for and read a command.
         */
        printf("Command: ");

        if (gets(buf) == NULL) {
            printf("\n");
            exit(0);
        }

        /*
         * Split the string into arguments.
         */
        parse(buf, args);

        /*
         * Execute the command.
         */
        execute(args);
    }
}

/*
* parse--split the command in buf into
*         individual arguments.
*/
void parse(char *buf, char **args)
{
    while (*buf != '\0') {
        /*
         * Strip whitespace. Use nulls, so
         * that the previous argument is terminated
         * automatically.
         */
        while ((*buf == ' ') || (*buf == '\t'))
            *buf++ = '\0';

        /*
         * Save the argument.
         */
        *args++ = buf;

        /*
         * Skip over the argument.
         */
        while ((*buf != '\0') && (*buf != ' ') && (*buf != '\t'))
            buf++;
    }

    *args = NULL;
}

/*
* execute--spawn a child process and execute
*           the program.
*/
void execute(char **args)

{
//fill in your code here
   pid_t pid;
   switch (pid = fork()) {
       case -1:
           perror("error");

       case 0:
           execvp(args[0], args);
           perror(*args);
           exit(1);
   }

0 0
Add a comment Improve this question Transcribed image text
Answer #1

In the code you have posted, the #include lines are clipped off. So I could not get the different files that are included. I did include them looking at code. So the order may be differnt from what you have in your original code. Just make sure you have <string.h> also for the new code to work. If you are not supposed to use string.h , let me know.

Modified code-
------------

/* The program asks for UNIX commands to be typed and inputted to a string*/
/* The string is then "parsed" by locating blanks etc. */
/* Each command and corresponding arguments are put in a args array */
/* execvp is called to execute these commands in child process */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>

void parse(char *buf, char **args);
void execute(char **args);

int main(int argc, char *argv[])
{
char buf[1024];
char *args[64];
int n = 0;
for (;;) {
/*
* Prompt for and read a command.
*/
printf("Command: ");
  
if (fgets(buf, 1024, stdin) == NULL) {
printf("\n");
exit(0);
}
  
   while(buf[n] != '\n')
       n++;
     
   buf[n] = '\0'; //remove the newline character at end
  
/*
* Split the string into arguments.
*/
parse(buf, args);

/*
* Execute the command.
*/
execute(args);
}
}

/*
* parse--split the command in buf into
* individual arguments.
*/
void parse(char *buf, char **args)
{
while (*buf != '\0') {
/*
* Strip whitespace. Use nulls, so
* that the previous argument is terminated
* automatically.
*/
while ((*buf == ' ') || (*buf == '\t'))
*buf++ = '\0';

/*
* Save the argument.
*/
*args++ = buf;

/*
* Skip over the argument.
*/
while ((*buf != '\0') && (*buf != ' ') && (*buf != '\t'))
buf++;
}

*args = NULL;
}

/*
* execute--spawn a child process and execute
* the program.
*/
void execute(char **args)

{
//fill in your code here
pid_t pid;
switch (pid = fork()) {
case -1:
perror("error");

case 0:
execvp(args[0], args);
perror(*args);
exit(1);
}
}

Add a comment
Know the answer?
Add Answer to:
The original code using the gets() function is written below. You need to do (a) change...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Edit the code (shell.c) given to do the tasks asked! will rate for correct answer! Also,...

    Edit the code (shell.c) given to do the tasks asked! will rate for correct answer! Also, include a screen shot of the output and terminal window of each command you used. Read carefully to do this task please. shell.c code given below. #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/wait.h> #include <string.h> int main() { int PID; char lineGot[256]; char *cmd; while (1){ printf("cmd: "); fgets(lineGot, 256, stdin); // Get a string from user (includes \n) cmd = strtok(lineGot, "\n");...

  • Run the code in Linux and provide the screenshot of the output and input #include <signal.h>...

    Run the code in Linux and provide the screenshot of the output and input #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> static void cleanup(); static void docleanup(int signum); static const char *SERVER_ADDR = "127.0.0.1"; static const int SERVER_PORT = 61234; static int cfd = -1; int main(int argc, char *argv[]) { struct sockaddr_in saddr; char buf[128]; int bufsize = 128, bytesread; struct sigaction sigact; printf("client starts running ...\n"); atexit(cleanup); sigact.sa_handler =...

  • Hello, how can i compile this C code using option -std=c99 or -std=gnu99 #include <stdio.h> #include...

    Hello, how can i compile this C code using option -std=c99 or -std=gnu99 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> static char* args[512]; pid_t pid; int command_pipe[2]; static void waiting(int n); static int command(int input, int first, int last) { int fd[2]; int flag=0; pipe( fd );   pid = fork(); if (pid == 0) { for(int i=0;args[i]!=0;i++) { if(args[i][0]=='>') { fd[1]=open(args[i+1], O_CREAT|O_TRUNC|O_WRONLY, 0644); flag=1; } if(args[i]=='>>' ) { fd[1]=open(args[i+1],...

  • Combine two codes (code 1) to get names with(code 2) to get info: Code 1: #include<unistd.h>...

    Combine two codes (code 1) to get names with(code 2) to get info: Code 1: #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<dirent.h> #include<stdio.h> #include<stdlib.h> void do_ls(char []); int main(int argc,char *argv[]) { if(argc == 1) do_ls("."); else while(--argc){ printf("%s:\n",*++argv); do_ls(*argv); } } void do_ls(char dirname[]) { DIR *dir_ptr; struct dirent *direntp; if((dir_ptr = opendir(dirname)) == NULL) fprintf(stderr,"ls1:cannot open %s\n",dirname); else { while((direntp = readdir(dir_ptr)) != NULL) printf("%s\n",direntp->d_name); closedir(dir_ptr); } } ____________________________ code 2: #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> void show_stat_info(char *,...

  • For Unix in a C/C++ environment echoServer and echoClient are provided below In this lab, we will...

    For Unix in a C/C++ environment echoServer and echoClient are provided below In this lab, we will modifiy echoServer.c and echoClient.c programs (for the server's port# not fixed). (1) Modify echoServer.c program to take one argument (a port number) to be used for its listening port when it starts. (2) Modify echoClient.c program to take two arguments (server's IP address and Port number) to be used for its connection. (3) Find a port free for the server using netstat (see...

  • need this in c programming and you can edit the code below. also give me screenshot...

    need this in c programming and you can edit the code below. also give me screenshot of the output #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #define LINE_SIZE 1024 void my_error(char *s) { fprintf(stderr, "Error: %s\n", s); perror("errno"); exit(-1); } // This funciton prints lines (in a file) that contain string s. // assume all lines has at most (LINE_SIZE - 2) ASCII characters. // // Functions that may be called in this function: // fopen(), fclose(), fgets(), fputs(),...

  • this is the code you should use from already existing shell i created . Just gothrough...

    this is the code you should use from already existing shell i created . Just gothrough the programand execute that command.and execute in linux. It takes the command from the user and execute. #include<stdio.h>i #include<stdlib.h> #include<string.h> int main() { //cmd1 is the ,hr variable which holds the commands char cmd1[10]; printf("Enter the command without options like ls or date"); scanf("%s",&cmd1); printf("%s\n",cmd1); //system function is used for to run the unix commad, it use system(cmd1); return 0; } #include<stdlib.h> int main()...

  • IN UNIX, MODIFY CODE, PROVIDE SCREENSHOTS FOR GOOD RATING: T1. Modify Client.c program to accept two...

    IN UNIX, MODIFY CODE, PROVIDE SCREENSHOTS FOR GOOD RATING: T1. Modify Client.c program to accept two arguments (IP add & port no. of the concurrent Server with thread - conServThread.c). Similarly, modify the Server (conServThread.c) program to accept an argument which is the port number of the server to bind and listen to. Try these two updated programs (server and client) with a port number (e.g., hhmm6) with current time where hh is hours in 24-hour format and mm is...

  • Assume I don't understand C++ Can someone explain this program to me Line by Line? Basically...

    Assume I don't understand C++ Can someone explain this program to me Line by Line? Basically what each line actually does? whats the function? whats the point? Don't tell me what the program does as a whole, I need to understand what each line does in this program. #include #include #include #include #include #define SERVER_PORT 5432 #define MAX_LINE 256 int main(int argc, char * argv[]) {    FILE *fp;    struct hostent *hp;    struct sockaddr_in sin;    char *host;...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT