Oh well I guess I just thought there was more to background.
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <iostream>
#include <stdlib.h>
using namespace std;
bool ParseArg(char* cmnd, char* cmd[], char input[],bool BG)
{
cout << "myshell> ";
cin.getline(input,50);
cmnd = strtok(input, " ");
int i = 0;
while(cmnd != NULL)
{
cmd = cmnd;
if(strcmp(cmd, "&") == 0){
//Debug cout << "& found";
cmd = NULL;
return true;
}
//Debug cout << cmd << " ";
i++;
cmnd = strtok(NULL, " ");
}
return false;
}
void Clean(char* cmd[])
{
//Clean Array
for(int a=0; a < 40; a++)
{
cmd[a] = NULL;
}
}
void Execute(char* cmd[],bool BG)
{
pid_t pid;
pid = fork();
switch(pid)
{
case -1:
cout << "DEBUG:Fork Failure" << endl;
exit(-1);
case 0:
execvp(cmd[0], cmd);
if(execvp(cmd[0], cmd) == -1)
{
cout << "Command Not Found" << endl;
exit(0);
}
default:
if(BG == 0)
{
wait(NULL);
cout << "DEBUG:Child Finished" << endl;
}
}
}
int main()
{
char* cmnd;
char* cmd[40];
char input[50];
bool BG = false;
while(cmd[0] != NULL)
{
Clean(cmd);
BG = ParseArg(cmnd, cmd, input, BG);
cout << BG;
if(strcmp(cmd[0], "exit") == 0 || strcmp(cmd[0], "quit") == 0 )
{
break;
}
else
{
Execute(cmd,BG);
}
}
return 1;
}
Thats my final code. I tested it.
here's my output, see if it "seems" right.
myshell> ls -l
total 36
-rwxr-xr-x 1 matt matt 8435 2010-09-26 20:43 a.out
-rw-r--r-- 1 matt matt 943 2010-09-26 20:44 fork.c
drwxr-xr-x 2 matt matt 4096 2010-09-27 02:13 Hello
-rwxr-xr-x 1 matt matt 8293 2010-09-27 18:50 shell
-rw-r--r-- 1 matt matt 1650 2010-09-27 18:50 shell.c
0DEBUG:Child Finished
myshell> ls -l &
1myshell> total 36
-rwxr-xr-x 1 matt matt 8435 2010-09-26 20:43 a.out
-rw-r--r-- 1 matt matt 943 2010-09-26 20:44 fork.c
drwxr-xr-x 2 matt matt 4096 2010-09-27 02:13 Hello
-rwxr-xr-x 1 matt matt 8293 2010-09-27 18:50 shell
-rw-r--r-- 1 matt matt 1650 2010-09-27 18:50 shell.c
ls -a
0DEBUG:Child Finished
myshell> . .. a.out fork.c Hello .hi shell shell.c
From what I can tell, when I call the & it doesn't wait for the myshell> to come back up, and just lets you call another command anyways. So it "seems" right.
Also I did the sleep 60 &, and it let me call ls right after, as opposed to without the & it had to wait. My only little issue "maybe" with it, is that after you call & once, the myshell>
doesn't come back up....although it still lets me type in commands. So I thought "well maybe it's treating them ALL as background processes"......but it's not, because I tried the sleep 60 thing after I had typed in an ls & previously and it made me wait 60 seconds..........so? I think it may just be a problem with the myshell> printout thing, altho im not sure what it is.
BTW, totally off topic, but is there any reason cd (change dir.) doesn't ever work on any of these "sample shells" i've seen around (when I was looking for help with mine, i looked at a ton of examples and tried a ton of them) is their something special about cd?