Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This code keeps giving me a sergetation fault #include <stdio.h> #include <unist

ID: 3901056 • Letter: T

Question

This code keeps giving me a sergetation fault

#include <stdio.h>

#include <unistd.h>

#define MAX_LINE 80 /* The maximum length command */

int main (void)

{

char *args[MAX_LINE/2 +1]; /* command line arguments */

int should_run = 1; /* flag to determine when to exit program */

while (should_run) {

printf("CSCI3120>");

fflush(stdout);

char *temp;

char *token;

int i = 0;

  

scanf("%s", &temp);

token = strtok(temp, " ");

while( token != NULL ){

args[i] = token;

printf(" %s ", token);

token = strtok(NULL, " ");

i = i + 1;

  

}

int j = 0;

while (i > j){

printf(args[j]);

j = j + 1;

}

  

  

  

/**

*After reading user input, the steps are:

*(1) fork a child process using fork()

*(2) the child process will invoke execvp()

*(3) if command included &, parent will invoke wait()

*/

}

return 0;

}

This args array will be passed to the execvp) function, which has the following prototype: execvp (char *command, char *params []) Here, command represents the command to be performed and params stores the to this command. For this project, the execvp( function should be invoked as parameters execvp (args[0], args) Be sure to check whether the user included an & to determine whether or not the parent process is to wait for the child to exit.

Explanation / Answer

#include <stdio.h>
#include <unistd.h>
#include<string.h>
#define MAX_LINE 80 /* The maximum length command */


void execute(char **argv)
{
     pid_t pid;
     int    status;

     if ((pid = fork()) < 0) {    
          printf("*** ERROR: forking child process failed ");
          return;
     }
     else if (pid == 0) {         
          if (execvp(*argv, argv) < 0) {   
               printf("*** ERROR: exec failed ");
               return;
          }
     }
     else {                               
          while (wait(&status) != pid)     
               ;
     }
}


int main (void)
{
char *args[MAX_LINE/2 +1]; /* command line arguments */
int should_run = 1; /* flag to determine when to exit program */
while (should_run) {
printf("CSCI3120>");
fflush(stdout);
char temp[MAX_LINE/2 +1];
char *token;
int i = 0;

printf("Enter command or exit to quit:");
scanf("%s", temp);
if (strcmp(temp,"exit") == 0)
   break;
token = strtok((char *)temp, " ");
while( token != NULL ){
//printf("------------------ ");
args[i] = token;
printf(" %s ", token);
token = strtok(NULL, " ");
i = i + 1;

}
int j = 0;
while (i >= j){
printf(args[j]);
j = j + 1;
}

/**
*After reading user input, the steps are:
*(1) fork a child process using fork()
*(2) the child process will invoke execvp()
*(3) if command included &, parent will invoke wait()
*/
execute(args);

}
return 0;
}