In: Computer Science
You are required to revise function shell_execute() in simple-execute.c, so the program can execute commands with up to two pipes. Basically, your program should be able to handle the case in which there is at least one space before or after “|” such as:
$$$ ls -l | grep D | wc -l
$$$ ls -l | grep D
If there is no space between or after “|”, for example, for the
following case:
$$$ ls|
“ls|” is treated as one argument to be executed (rather than “ls” and “|”)
The simple-execute.c code:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
int shell_execute(char ** args, int argc)
{
int child_pid, wait_return, status;
if ( strcmp(args[0], "EXIT") == 0 )
return -1;
if( (child_pid = fork()) < 0 )
{
printf("fork() error \n");
}
else if (child_pid == 0 )
{
if ( execvp(args[0], args) <
0){
printf("execvp()
error \n");
exit(-1);
}
}else
{
if ( (wait_return =
wait(&status) ) < 0 )
printf("wait()
error \n");
}
return 0;
}
First create a file named file.sh and execute the command:
chmod 777 file.sh
The code for shell_execute will be as follows:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
int shell_execute(int argc, char *args[])
{
int child_pid, wait_return, status,i;
if ( strcmp(args[0], "EXIT") == 0 )
return -1;
if( (child_pid = fork()) < 0 )
{
printf("fork() error
\n");
}
else if (child_pid == 0 )
{
FILE *f=fopen("file.sh","w");
fprintf(f,"#!/bin/sh\n");
for(i=1;i<argc;i++)
{
fprintf(f,"%s\nexit",args[i]);
}
fclose(f);
if (
execl("file.sh","file.sh",NULL) < 0){
printf("%s\n",args[1]);
exit(-1);
}
}else
{
if ( (wait_return =
wait(&status) ) < 0 )
printf("wait() error \n");
}
return 0;
}