Hi I've recently started learning unix system programming.
I'm trying to create a minishell in c but when I run my code,
I always get:
EXC_BAD_ACCESS (code=EXC_I386_GPFLT
Don't really know what's wrong here. Searched online they say it's something wrong with malloc, but I don't see what's wrong.
Can someone help me with this problem?
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
#include "minishell.h"
char promptString[] = "mysh>";
struct command_t command;
int enviromentlength;
int commandlength;
char *pathv[MAX_PATHS];
//to display the prompt in the front of every line
void printPrompt()
{
printf("%s", promptString);
}
//get the user's command
void readCommand(char *buffer)
{
gets(buffer);
}
//get the environment variable and store in a pathEnvVar
int parsePath( char* dirs[] )
{
char* pathEnvVar;
char* thePath;
int i;
for(i = 0; i < MAX_ARGS; i++)
{
dirs[i] = NULL;
}
i = 0;
//use system call to get the environment variable
pathEnvVar = (char*) getenv("PATH");
//printf("%s\n", pathEnvVar);
thePath = (char*) malloc(strlen(pathEnvVar) + 1);
strcpy(thePath, pathEnvVar);
//splict the variable and store in the pathv
char *temp = strtok(thePath, ":");
dirs[i] = temp;
while(temp != NULL)
{
i++;
temp = strtok(NULL, ":");
if(temp == NULL)
{
break;
}
else
{
dirs[i] = temp;
}
}
dirs[i+1] = NULL;
return i;
}
//get the user's command and parameters
int parseCommand(char * commandline)
{
int i = 0;
char* temp;
temp = strtok(commandline, " ");
while(temp != NULL)
{
command.argv[i] = temp;
i++;
temp = strtok(NULL, " ");
}
command.argv[i] = NULL;
return i;
}
//input the user's command to
//fix the absolute path of the command
char* lookupPath(char* dir[], char* command[])
{
char* result = NULL;
int i;
//printf("%c\n", *command.argv[0]);
//if the command is already an absolute path
if(*command[0] == '/')
{
result = command[0];
//printf("test\n");
if( access(result, X_OK) == 0)
{
return result;
}
else
{
fprintf(stderr, "%s: command not found\n", result);
return NULL;
}
}
//if the command is not an absolute path
else
{
for(i = 0; i < enviromentlength; i++)
{
char *temp = (char *) malloc (30);
strcpy(temp, dir[i]);
strcat(temp, "/");
strcat(temp, command[0]);
result = temp;
if( access(result, X_OK) == 0)
{
return result;
}
}
fprintf(stderr, "%s: command not found\n", result);
return NULL;
}
}
//to change the directory and
//display the absolute path of the current directory
void do_cd(char* dir[])
{
char currentdirectory[MAX_PATHS];
if(dir[1] == NULL || (strcmp(dir[1], ".") == 0))
{
printf("director does not change\n");
//printf("The current directory is:%s", currentdirectory);
}
else
{
if(chdir(dir[1]) < 0)
{
printf("change director error\n");
}
else
{
printf("change director success\n");
}
}
getcwd(currentdirectory, MAX_PATHS);
printf("The current directory is:%s\n", currentdirectory);
}
//redirection the result to file
void redirection(char* command, char* commandcontent[], int position, pid_t thisChPID)
{
char* content[commandlength - 1];
char* filename = (char *) malloc(MAX_PATH_LEN);
FILE* fid;
int i = 0;
int stat;
strcpy(filename, commandcontent[position + 1]);
//printf("%s\n", commandcontent[position + 1]);
for(i = 0; i < position; i++)
{
content[i] = commandcontent[i];
//printf("content: %s\n", content[i]);
}
content[i + 1] = NULL;
for(i = 0; i< position + 1; i++)
{
printf("%s\n", content[i]);
}
printf("%s\n", command);
if((thisChPID=fork()) < 0)
{
fprintf(stderr, "fork failed\n");
}
else if(thisChPID == 0)
{
fid = open(filename, O_WRONLY || O_CREAT);
close(1);
dup(fid);
close(fid);
execve(command, content, pathv);
}
else
{
wait(&stat);
}
}
//use pipe to run the program
void piperun(char* command, char* commandcontent[], int position, pid_t thisChPID)
{
printf("%s\n%d\n", command, position);
char* firstcommand[position+1];
char* secondcommand[commandlength-position];
char* result = (char *) malloc(MAX_PATH_LEN);
pid_t child;
//the pipe name
int pipeID[2];
int j;
for(j = 0; j< position; j++)
{
firstcommand[j] = commandcontent[j];
printf("%s\n", firstcommand[j]);
}
firstcommand[j] = NULL;
printf("length: %d\n", commandlength-position);
for(j = 0; j < (commandlength-position); j++)
{
secondcommand[j] = commandcontent[position + 1 + j];
printf("second:%s\n",secondcommand[j]);
}
//secondcommand[j+1] = NULL;
result = lookupPath(pathv, secondcommand);
//printf("%s\n", secondcommand[0]);
printf("%s\n", result);
//create pipe "pipeID"
if(pipe(pipeID)==-1)
{
printf("Fail to creat pipe.\n");
}
if((thisChPID=fork())==-1)
{
printf("Fail to creat child process.\n");
}
if(thisChPID==0)
{
printf("in the child\n");
close(1);
dup(pipeID[1]);
close(pipeID[0]);
close(pipeID[1]);
if(execve(command, firstcommand, pathv)==-1)
{
printf("Child process can't exec command %s.\n",firstcommand[0]);
}
}
else
{
child = fork();
if((child=fork())==-1)
{
printf("Fail to creat child process.\n");
}
if(child==0)
{
close(0);
dup(pipeID[0]);
close(pipeID[1]);
close(pipeID[0]);
if(execve(result, secondcommand, pathv)==-1)
{
printf("Child process can't exec command %s.\n",secondcommand[0]);
}
}
else
{
wait(NULL);
}
}
}
int main()
{
char commandLine[LINE_LEN];
int child_pid; //child process id
int stat; //used by parent wait
pid_t thisChPID;
char *arg[MAX_ARGS];
//the flag of redirection, piping and background running
int redirectionsituation = 0;
int pipesituation = 0;
int background = 0;
char * tempchar;
//Command initialization
int i;
for(i = 0; i < MAX_ARGS; i++ )
{
command.argv[i] = (char *) malloc(MAX_ARG_LEN);
}
//get all directories from PATH env var
enviromentlength = parsePath(pathv);
//Main loop
while(TRUE)
{
redirectionsituation = 0;
pipesituation = 0;
background = 0;
//Read the command line
printPrompt();
readCommand(commandLine);
//input nothing
if(commandLine[0] == '\0')
{
continue;
}
//quit the shell?
if((strcmp(commandLine, "exit") == 0) || (strcmp(commandLine, "quit") == 0))
{
break;
}
//if it is background running
if(commandLine[strlen(commandLine) - 1] == '&')
{
printf("backgrond\n");
tempchar = strtok (commandLine, "&");
//strcpy(commandLine, tempchar);
printf("%s\n", tempchar);
background = 1;
}
//Parse the command line
commandlength = parseCommand(commandLine);
//if the command is "cd"
if(strcmp(command.argv[0], "cd") == 0)
{
do_cd(command.argv);
continue;
}
//Get the full path name
command.name = lookupPath(pathv, command.argv);
printf("command name %s\n", command.name);
//report error
if( command.name == NULL)
{
continue; //non-fatal
}
//if redirection is required
for(i = 0; i < commandlength; i++)
{
if(strcmp(command.argv[i], ">") == 0)
{
redirectionsituation = 1;
break;
}
}
if(redirectionsituation == 1)
{
redirection(command.name, command.argv, i, thisChPID);
continue;
}
//if pipe is required
for(i = 0; i < commandlength; i++)
{
if(strcmp(command.argv[i], "|") == 0)
{
pipesituation = 1;
break;
}
}
if(pipesituation == 1)
{ //run pipe
piperun(command.name, command.argv, i, thisChPID);
continue;
}
//normal running
if((thisChPID=fork()) < 0)
{
fprintf(stderr, "fork failed\n");
}
else if(thisChPID == 0)
{
//printf("run again\n");
execve(command.name, command.argv, pathv);
}
else
{
//do not put the process in the background, wait until the child process terminates
if(background == 0)
{
wait(&stat);
}
}
}
return 0;
}
Run it in a debugger and see where you are dereferencing a null.
Related
I am currently working on a program in which I have to write a shell in C. I am having trouble getting the fork() section of my program to work. Here is my code:
void execute_func(char** tok)
{
pid_t pid = fork();
if (pid == -1)
{
printf("\nERROR: forking child process failed\n");
return;
}
else if (pid == 0)
{
if (execvp(tok[0], tok) < 0)
{
printf("ERROR: exec failed\n");
}
exit(0);
}
else
{
wait(NULL);
return;
}
}
for example, if I am to type in any sort of function such as "ls" or "wc" it gives me the "ERROR: exec failed" message, which means that the fork() is not running correctly. This could be a small issue in my understanding of fork() but I am completely stumped.
here is my whole program:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
char str[129];
enum {NOT_FOUND=0,FOUND};
enum {false=0,true};
static char *ptr;
const char *del;
int ReadLine(char *, int , FILE *);
char *mystrtok(char* string,const char *delim)
{
int j,flag=NOT_FOUND;
char *p;
if(string != NULL)
{
ptr=string;
p=string;
}
else
{
if(*ptr == '\0')
return NULL;
p=ptr;
}
while(*ptr != '\0')
{
del=delim;
while(*del != '\0')
{
if(*ptr == *del)
{
if(ptr == p)
{
p++;
ptr++;
}
else
{
*ptr='\0';
ptr++;
return p;
}
}
else
{
del++;
}
}
ptr++;
}
return p;
}
void execute_func(char** tok)
{
pid_t pid = fork();
if (pid == -1)
{
printf("\nERROR: forking child process failed\n");
return;
}
else if (pid == 0)
{
if (execvp(tok[0], tok) < 0)
{
printf("ERROR: exec failed\n");
}
exit(0);
}
else
{
wait(NULL);
return;
}
}
int main()
{
int i;
char *p_str,*token;
char delim[10];
delim[0] = ' ';
delim[1] = '\t';
delim[2] = '\n';
delim[3] = '\0';
char cwd[1024];
char *tok[129];
while(1)
{
tok[0] = NULL;
fflush(stdin);
fflush(stdout);
printf("\n Enter a string to tokenize: ");
// printf("\n before scan");
fflush(stdin);
// printf("\n fflush");
ReadLine(str, 128, stdin);
/* scanf("%[^\n]",str); */
printf("\n after scan");
for (i = 1, p_str = str; ; i++, p_str = NULL)
{
token = mystrtok(p_str,delim);
if (token == NULL)
break;
printf("%d: %s\n",i,token);
tok[i-1] = token;
printf("%s\n",tok[i-1]);
}
if(tok[0] != NULL)
{
if(strcmp(tok[0],"cd") == 0)
{
if (chdir(tok[1]) != 0)
perror("chdir() error()");
getcwd(cwd, sizeof(cwd));
printf("current working directory is: %s\n", cwd);
}
else if(strcmp(tok[0],"pwd") == 0)
if (getcwd(cwd, sizeof(cwd)) == NULL)
perror("getcwd() error");
else
printf("current working directory is: %s\n", cwd);
else if(strcmp(tok[0],"exit") == 0)
exit(3);
else
{
execute_func(tok);
}
}
}
}
int ReadLine(char *buff, int size, FILE *fp)
{
buff[0] = '\0';
buff[size - 1] = '\0'; /* mark end of buffer */
char *tmp;
if (fgets(buff, size, fp) == NULL)
{
*buff = '\0'; /* EOF */
return false;
}
else
{
/* remove newline */
if ((tmp = strrchr(buff, '\n')) != NULL)
{
*tmp = '\0';
}
}
return true;
}
Problem appears to be here:
if (token == NULL)
break;
printf("%d: %s\n",i,token);
tok[i-1] = token;
The trailing NULL never gets set in tok thus resulting in execve not finding the end of the list. Like this should fix it:
tok[i-1] = token;
if (token == NULL)
break;
printf("%d: %s\n",i,token);
I'm creating a shell in C and have implemented piping. This involves dividing the argument on the left side and right side of the pipe into two separate array of strings to be executed separately with execvp. For some reason, the array of strings pcmd2 contains data other than the argument I entered in the shell.
For example, I enter ls | sort into the shell after running the program and it outputs the following: sort: open failed: : No such file or directory
Seeing this, I suspected that the array of strings pcmd2 containing the sort command may have empty strings and other things that are being processed.
I print out pcmd2 with a for-loop (with a new line after each string) and I find the following printed onto the screen:
sort
UJ
There clearly seems to be extra stuff in there. Seems like empty strings but I have no clue where the UJ is coming from (this gets consistenly printed out).
I've tried setting the index in pcmd2 that's right after where sort is stored in the array to NULL. Like so, pcmd2[1] = NULL and that seemed to "fix" it since the weird extra data would no longer be processed by the execvp function. However, that means that I can't pipe commands with multiple arguments like grep myshell as it would only be able to take in the grep part.
I will show the full code below because I'm unsure how much context is needed in this case.
I know there's some very broken piping implementation here (I've tried some weird solution to get it work with two pipes) but I'm working to just get one pipe to work. I'm not asking for help piping in particular.
The most relevant part, I believe, is in the splitPipeCommands function.
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#define MAX_ARGS 20
#define MAX_PIPE_ARGS 3
#define BUFSIZE 1024
int input, output, append, usePipe;
char *inputFile;
char *outputFile;
FILE *fp1;
FILE *fp2;
int get_args(char* cmdline, char* args[])
{
int i = 0;
/* if no args */
if((args[0] = strtok(cmdline, "\n\t ")) == NULL)
return 0;
while((args[++i] = strtok(NULL, "\n\t ")) != NULL) {
if(i >= MAX_ARGS) {
printf("Too many arguments!\n");
exit(1);
}
}
/* the last one is always NULL */
return i;
}
void checkIORedirect(char* args[])
{
input = 0;
output = 0;
append = 0;
int i;
for(i = 0; args[i] != NULL; i++)
{
if(!strcmp(args[i], ">"))
{
output = 1;
outputFile = args[i+1];
args[i] = NULL;
}
else if(!strcmp(args[i], "<"))
{
input = 1;
inputFile = args[i+1];
args[i] = NULL;
//printf("inputFile: %s\n", inputFile);
}
else if(!strcmp(args[i], ">>"))
{
append = 1;
outputFile = args[i+1];
args[i] = NULL;
}
}
}
int getPipeIndexes(char* args[], int* pIndex1, int* pIndex2)
{
*pIndex1 = -1;
*pIndex2 = -1;
int i = 0;
int pcount = 0;
usePipe = 0;
for(i = 0; args[i] != NULL; i++)
{
if(!strcmp(args[i], "|") && pcount == 0)
{
//printf("First pipe!\n");
*pIndex1 = i;
args[i] = NULL;
pcount++;
usePipe = 1;
}
else if(!strcmp(args[i], "|") && pcount == 1)
{
//printf("Second pipe!\n");
*pIndex2 = i;
args[i] = NULL;
pcount++;
}
else if(!strcmp(args[i], "|") && pcount > 1)
{
printf("Too many pipes, only accepting first two!\n");
args[i] = NULL;
}
}
return pcount;
}
void splitPipeCommands(char* args[], int* pIndex1, int* pIndex2, int pcount, char* pcmd1[], char* pcmd2[], char* pcmd3[])
{
if(pcount == 1)
{
int i;
int cmdIndex = 0;
for(i = 0; i < *pIndex1; i++)
{
pcmd1[cmdIndex] = args[i];
cmdIndex++;
}
cmdIndex = 0;
//printf("2nd half of args: \n");
for(i = *pIndex1 + 1; args[i] != NULL; i++)
{
pcmd2[cmdIndex] = args[i];
//printf("%s\n", args[i]);
cmdIndex++;
}
//pcmd2[1] = NULL;
//*pcmd1 = args[0];
//*pcmd2 = args[*pIndex1 + 1];
/*TODO: del when you finish debugging*/
//printf("pcmd1=%s,%s,%s\n", pcmd1[0], pcmd1[1], pcmd1[2]);
//printf("pcmd2=%s\n", pcmd2[0]);
}
else if(pcount == 2)
{
int i;
int cmdIndex = 0;
for(i = 0; i < *pIndex1; i++)
{
pcmd1[cmdIndex] = args[i];
cmdIndex++;
}
cmdIndex = 0;
for(i = *pIndex1 + 1; i < *pIndex2; i++)
{
pcmd2[cmdIndex] = args[i];
cmdIndex++;
}
//pcmd2[1] = NULL;
cmdIndex = 0;
for(i = *pIndex2 + 1; args[i] != NULL; i++)
{
pcmd3[cmdIndex] = args[i];
cmdIndex++;
}
/*
*pcmd1 = args[0];
*pcmd2 = args[*pIndex1 + 1];
*pcmd3 = args[*pIndex2 + 1];
*/
/*TODO: del when you finish debugging*/
//printf("pcmd1=%s,", *pcmd1);
//printf("pcdm2=%s,", *pcmd2);
//printf("pcmd3=%s\n", *pcmd3);
}
}
void closeFiles()
{
if(fp1 != NULL)
{
fclose(fp1);
}
if(fp2 != NULL)
{
fclose(fp2);
}
}
void execute(char* cmdline)
{
int pid, pid2, async;
char* args[MAX_ARGS];
int nargs = get_args(cmdline, args);
if(nargs <= 0) return;
if(!strcmp(args[0], "quit") || !strcmp(args[0], "exit")) {
exit(0);
}
/* check if async call */
if(!strcmp(args[nargs-1], "&")) { async = 1; args[--nargs] = 0; }
else async = 0;
/*Pipe related*/
int pIndex1, pIndex2;
char* pcmd1[30];
char* pcmd2[30];
char* pcmd3[30];
int pcount = getPipeIndexes(args, &pIndex1, &pIndex2);
if(usePipe)
{
splitPipeCommands(args, &pIndex1, &pIndex2, pcount, pcmd1, pcmd2, pcmd3);
if(pcount == 1)
{
checkIORedirect(pcmd1);
checkIORedirect(pcmd2);
}
else if(pcount == 2)
{
checkIORedirect(pcmd1);
checkIORedirect(pcmd2);
checkIORedirect(pcmd3);
}
}
else
{
checkIORedirect(args);
}
/*TODO: del when finished debugging*/
//printf("pIndex1=%d,pIndex2=%d,pcount=%d\n", pIndex1, pIndex2, pcount);
//checkIORedirect(args);
if(output)
{
if((fp1 = fopen(outputFile, "w")) == NULL)
{
printf("Output to file failed!\n");
}
}
else if(append)
{
if((fp1 = fopen(outputFile, "a")) == NULL)
{
printf("Append to file failed!\n");
}
}
if(input)
{
if((fp2 = fopen(inputFile, "r")) == NULL)
{
printf("Input from file failed!\n");
}
}
int fd[2];
int fd2[2];
if(usePipe)
{
if(pipe(fd) == -1)
{
perror("pipe failed");
exit(1);
}
}
pid = fork();
if(pid == 0) { /* child process */
if(input)
{
//printf("Input\n");
dup2(fileno(fp2), STDIN_FILENO);
fclose(fp2);
input = 0;
}
if(output || append)
{
dup2(fileno(fp1), STDOUT_FILENO);
fclose(fp1);
output = 0;
append = 0;
//printf("Output or append\n");
}
if(usePipe)
{
//TODO: Make case for one pipe and two pipes
if(pcount == 2)
{
if(pipe(fd2) == -1)
{
perror("pipe failed");
exit(1);
}
pid2 = fork();
if(pid2 == -1)
{
perror("fork 2 failed");
exit(1);
}
if(pid2 == 0) //Child 2
{
close(fd[1]);
close(fd[0]);
close(fd2[1]);
dup2(fd2[0], 0);
close(fd2[0]);
execvp(pcmd2[0], pcmd2);
perror("exec second child failed");
exit(-1);
}
else //Child 1
{
close(fd[1]);
dup2(fd[0], 0);
close(fd[0]);
close(fd2[0]);
dup2(fd2[1], 1);
close(fd2[1]);
execvp(pcmd3[0], pcmd3);
perror("exec first child failed");
exit(-1);
}
}
else if(pcount == 1)
{
//TODO: pipe for one pipe
//close(fd[1]);
//dup2(fd[0], 0);
dup2(fd[1], STDOUT_FILENO);
close(fd[0]);
close(fd[1]);
printf("pcmd1=%s\n", pcmd1[0]);
execvp(pcmd1[0], pcmd1);
perror("exec child failed");
exit(-1);
}
}
else
{
execvp(args[0], args);
/* return only when exec fails */
perror("exec failed");
exit(-1);
}
/*
execvp(args[0], args);
// return only when exec fails
perror("exec failed");
exit(-1);
*/
} else if(pid > 0) { /* parent process */
if(usePipe)
{
pid=fork();
if(pid==0)
{
dup2(fd[0], STDIN_FILENO);
close(fd[1]);
close(fd[0]);
printf("pcmd2 contents: \n");
int j;
for(j = 0; pcmd2[j] != NULL; j++)
{
printf("%s\n", pcmd2[j]);
}
//FIXME: Something's wrong with pcmd2
execvp(pcmd2[0], pcmd2);
//execlp("sort", "sort", (char*)NULL);
perror("exec second command failed");
}
else
{
int status;
close(fd[0]);
close(fd[1]);
waitpid(pid, &status, 0);
}
//wait(NULL);
/*
close(fd[0]);
dup2(fd[1], 1);
printf("pcmd1=%s\n", pcmd1[0]);
execvp(pcmd1[0], pcmd1);
perror("exec parent failed");
*/
}
if(!async)
{
waitpid(pid, NULL, 0);
}
else
{
printf("this is an async call\n");
}
} else { /* error occurred */
perror("fork failed");
exit(1);
}
}
int main (int argc, char* argv [])
{
char cmdline[BUFSIZE];
for(;;) {
printf("COP4338$ ");
if(fgets(cmdline, BUFSIZE, stdin) == NULL) {
perror("fgets failed");
exit(1);
}
execute(cmdline);
usePipe = 0;
//closeFiles();
fflush(stdout);
}
return 0;
}
I have written a function for the purposes of redirecting output from some command to a file. Something like this
ls > ls.txt
Here is the function that does output redirection:
int redirect_output(char* cmdline, char **output_filename) {
int i;
char* args[MAX_ARGS];
// int nargs = get_args(cmdline, args);
for(i = 0; args[i] != NULL; i++) {
// Look for the >
if(!strcmp(args[i], ">")) {
// Get the filename
if(args[i+1] != NULL) {
*output_filename = args[i+1];
} else {
return -1; //syntax error
}
return 1; //there is an >
}
}
return 0; //no redirect
}
The function successfully redirects output from some command to a file, but for some reason it causes other commands to stop working. So for example, my program with redirect_output works for something like ls but it does not work for something like cat ls.txt, if I do not call the function it works for any command. And, by not work it mean it gets stuck. Here are the other important functions.
int get_args(char* cmdline, char* args[])
{
int i = 0;
/* if no args */
if((args[0] = strtok(cmdline, "\n\t ")) == NULL)
return 0;
while((args[++i] = strtok(NULL, "\n\t ")) != NULL) {
if(i >= MAX_ARGS) {
printf("Too many arguments!\n");
exit(1);
}
}
/* the last one is always NULL */
return i;
}
void execute(int output, char *outputefile, char* cmdline)
{
int pid, async;
char* args[MAX_ARGS];
int nargs = get_args(cmdline, args);
if(nargs <= 0) return;
if(!strcmp(args[0], "quit") || !strcmp(args[0], "exit")) {
exit(0);
}
/* check if async call */
if(!strcmp(args[nargs-1], "&")) {
async = 1;
args[--nargs] = 0;
}
else async = 0;
pid = fork();
if(pid == 0) { /* child process */
//if(output)
// freopen(outputefile, "w+", stdout);
execvp(args[0], args);
/* return only when exec fails */
perror("exec failed");
exit(-1);
} else if(pid > 0) { /* parent process */
if(!async) waitpid(pid, NULL, 0);
else printf("this is an async call\n");
} else { /* error occurred */
perror("fork failed");
exit(1);
}
}
And here is my main:
int main (int argc, char* argv [])
{
char cmdline[BUFSIZ];
char *output_filename;
char **args;
int output;
for(;;) {
printf("COP4338$ ");
if(fgets(cmdline, BUFSIZ, stdin) == NULL) {
perror("fgets failed");
exit(1);
}
output = redirect_output(cmdline, &output_filename);
switch(0) {
case -1:
printf("Syntax error!\n");
break;
case 0:
break;
case 1:
printf("Redirecting output to: %s\n", output_filename);
break;
}
execute (output, output_filename, cmdline);
}
return 0;
}
Any help will be much appreciated! Thanks!
My code is not working and it is when I call fgets in the commandSplit function. I figured this out by printing "Am I here" in multiple places and find that the error at fgets it seems. I may be wrong, but I am pretty sure. I get a segmentation fault and I can not figure out why. Below is my code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#define MAX_CHARACTERS 512
int Execute(char *a[], int t[], int num) {
int exitShell = 0;
int l = 0;
for (int i = 0; i < num; i++) {
int status;
if (strcmp(a[0], "quit") == 0) {
exitShell = 1;
}
if (t[i] && ((strcmp(a[l], "quit") == 0))) {
exitShell = 1;
}
char *holder[t[i]+1];
for (int j = 0; j < t[i]; j++) {
holder[j] = a[l];
l++;
}
holder[t[i]] = NULL;
pid_t p = fork();
pid_t waiting;
if (p == 0) {
execvp(holder[0], holder);
fprintf(stderr, "Child process could not execvp!\n");
exit(1);
} else {
if (p < 0) {
fprintf(stderr, "Fork FAILED!\n");
} else {
waiting = wait(&status);
printf("Child %d exit with status %d\n", waiting, status);
}
}
for (int g = 0; g < t[i]; g++) {
a[g] = NULL;
}
}
for (int i = 0; i < num; i++) {
t[i] = 0;
}
return exitShell;
}
int commandSplit(char *c, FILE *f, char *a[], int t[]) {
int count = 0;
int emptyfile = 1;
int stat = 0;
int total1 = 0;
char *temp[MAX_CHARACTERS];
if (c != NULL) {
char *readCommands = strtok(c, ";");
while (readCommands != NULL) {
temp[count] = readCommands;
count++;
readCommands = strtok(NULL, ";");
}
for (int i = 0; i < count; i++) {
char *read = strtok(temp[i], " ");
int track1 = 0;
while (read != NULL) {
a[total1] = read;
track1++;
total1++;
read = strtok(NULL, " ");
}
t[i] = track1;
}
stat = Execute(a, t, count);
} else {
char *buildCommands = "";
printf("Am I here???\n");
while ((fgets(buildCommands, MAX_CHARACTERS, f) != NULL) && !stat) {
printf("Am I here???\n");
emptyfile = 0;
commandSplit(buildCommands, NULL, a, t);
stat = Execute(a, t, count);
}
if (emptyfile) {
printf("File is empty!\n");
stat = 1;
}
}
printf("Am I here???\n");
return stat;
}
int main(int argc, char *argv[]) {
int exitProgram = 0;
FILE *fileRead = NULL;
if (argc == 2) {
fileRead = fopen(argv[1], "r");
if (fileRead == NULL) {
printf("No such file exists\n");
exitProgram = 1;
}
}
if (argc > 2) {
printf("Incorrect batch mode call\n");
exitProgram = 1;
}
char *args[MAX_CHARACTERS];
int tracker[MAX_CHARACTERS];
while (!exitProgram) {
if (argc == 1) {
char *commands = (char *)(malloc(MAX_CHARACTERS * sizeof(char)));
printf("tinyshell>");
if (fgets(commands, MAX_CHARACTERS, stdin) == NULL) {
exitProgram = 1;
printf("\n");
}
int len;
len = strlen(commands);
if (len > 0 && commands[len-1] == '\n') {
commands[len-1] = '\0';
}
if (len > MAX_CHARACTERS) {
printf("TOO MANY CHARACTERS - MAX: 512\n");
continue;
}
if (strlen(commands) == 0)
continue;
exitProgram = commandSplit(commands, NULL, args, tracker);
} else {
exitProgram = commandSplit(NULL, fileRead, args, tracker);
}
}
fclose(fileRead);
return 0;
}
As commented #Jean-François Fabre , buildCommands points to insufficient space and potential const space;
char *buildCommands = "";
...
// bad code
while ((fgets(buildCommands, MAX_CHARACTERS, f) != NULL) && !stat) {
Allocate space with an array or malloc()
char buildCommands[MAX_CHARACTERS];
...
while ((fgets(buildCommands, sizeof buildCommands, f) != NULL) && !stat) {
...
}
// or
char *buildCommands = malloc(MAX_CHARACTERS);
assert(buildCommands);
...
while ((fgets(buildCommands, MAX_CHARACTERS, f) != NULL) && !stat) {
...
}
...
free(buildCommands);
I am currently writing a shell for school purposes and I have the problem that if I write the command "history", the "exit" command afterwards doesn't work. If you could help me I would be very happy.
Here is my code:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#define MAX_INPUT 256
static char cwd[100];
void myprintf(char *text) {
text != NULL ?
printf("%s#rash:%s: %s\n", getenv("USER"), getcwd(cwd, sizeof(cwd)), text) :
printf("%s#rash:%s: ", getenv("USER"), getcwd(cwd, sizeof(cwd)));
}
void errprintf(char *text) {
myprintf(NULL);
printf("Couldn't run %s\n", text);
}
static char *argv[256];
static int argc;
static int pid = 0;
FILE *fhistory;
void parseInput(char *input) {
input = strtok(input, "\n");
for (argc = 0; argc < MAX_INPUT; argc++) {
argv[argc] = NULL;
}
argc = 0;
fprintf(fhistory, "%s\n", input);
char *param = strtok(input, " ");
while (param) {
argv[argc++] = param;
param = strtok(NULL, " ");
}
}
void signalHandler(int sign) {
switch (sign) {
case SIGINT: {
if (pid != 0) {
kill(pid, SIGKILL);
pid = 0;
}
break;
}
case SIGCHLD: {
if (pid != 0) {
kill(pid, SIGKILL);
pid = 0;
}
break;
}
}
}
int programs() {
if (!strcmp(argv[0], "exit")) {
return -1;
}
if (!strcmp(argv[0], "cd")) {
chdir(argv[1] == NULL ? getenv("HOME") : argv[1]);
} else {
pid = fork();
switch (pid) {
case -1: {
myprintf("Erectile Dysfunction!");
break;
}
case 0: {
if (!strcmp(argv[0], "history")) {
system("cat .rash_history.txt");
} else {
execvp(argv[0], argv);
errprintf(argv[0]);
}
break;
}
default: {
waitpid(pid, NULL, 0);
signal(SIGCHLD, signalHandler);
return 0;
}
}
}
return 1;
}
int main(void) {
signal(SIGINT, signalHandler);
char *input = NULL;
myprintf("Welcome to rash!");
fhistory = fopen(".rash_history.txt", "a");
while (input != NULL ? strncmp(input, "exit", strlen(input)) != 0 : 1) {
myprintf(NULL);
input = (char *) malloc(sizeof(char *) * MAX_INPUT);
int j;
for (j = 0; j < MAX_INPUT; j++) {
input[j] = '\0';
}
fgets(input, MAX_INPUT, stdin);
parseInput(input);
if (*(input) != '\n') {
programs();
}
}
fclose(fhistory);
return 0;
}
I think here while (input != NULL ? strncmp(input, "exit", strlen(input)) != 0 : 1) {
it would be strlen("exit")
The "input" variable take value inside your while loop only:
fgets(input, MAX_INPUT, stdin);
parseInput(input);
The parseInput uses strtok function couple times. The strtok modifies the argument string, so it not clear what value it will contains at time you will compare it with "exit".
Try to duplicate "input" string before calling strtok. Try to add debug string at the end of loop to make clear what value is into input string.