#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <stdbool.h>
#include <time.h>
#define MAX_STR 10
#define MAX_CH 100
void logFile(const char* str)
{
time_t t = time(0);
/* open the file for writing*/
FILE *fp;
fp = fopen("log.txt", "w");
fprintf(fp, "%s %s\n",str,ctime(&t));
/* close the file*/
fclose (fp);
}
void read_line(char linechar[]) {
char* str = fgets(linechar,MAX_CH,stdin);
int i=0;
while(linechar[i]!='\n'){ //remove \n from end of line
i++;
}
linechar[i] = '\0';
if(str == NULL || strcmp(linechar,"exit") == 0){
exit(0);
}
}
bool line_parser(char* linestr[],char linechar[])
{
int i = 0;
bool flag = false;
linestr[i]= strtok(linechar," ");
if(linestr[i] == NULL){
printf("NO COMMAND\n");
}
while(linestr[i] != NULL){
i++;
linestr[i]= strtok(NULL," ");
}
if(i!=0 && strcmp(linestr[i-1] ,"&") == 0){ //check if the command includes "&" which means that the parent will no wait for child to finish
flag = true;
linestr[i - 1] = NULL;
}
return flag;
}
void SIGHandler(){
pid_t pid;
pid = wait(NULL);
if(pid>0) {
logFile("child process was terminated");;
}
}
bool line_Organizer(char* linestr[],char linechar[],bool flag){
printf("shell:~$ ");
read_line(linechar);
return line_parser(linestr,linechar);
}
int main()
{
char* linestr[MAX_STR];
char linechar[MAX_CH];
bool flag;
while(1){
bool flag = line_Organizer(linestr,linechar,flag);
pid_t pid = fork();
signal(SIGCHLD,SIGHandler);
if (pid < 0) {
perror("Fork failed");
exit(1);
}
else if(pid == 0) { //child
execvp(linestr[0],linestr);
if (execvp(linestr[0],linestr) < 0) {
printf("ERROR: Invalid command\n");
break;
}
} else { //parent
if(flag) {
flag = false;
continue;
}
waitpid(pid,0);
}
}
return 0;
}
{"html5":"htmlmixed","css":"css","javascript":"javascript","php":"php","python":"python","ruby":"ruby","lua":"text\/x-lua","bash":"text\/x-sh","go":"go","c":"text\/x-csrc","cpp":"text\/x-c++src","diff":"diff","latex":"stex","sql":"sql","xml":"xml","apl":"apl","asterisk":"asterisk","c_loadrunner":"text\/x-csrc","c_mac":"text\/x-csrc","coffeescript":"text\/x-coffeescript","csharp":"text\/x-csharp","d":"d","ecmascript":"javascript","erlang":"erlang","groovy":"text\/x-groovy","haskell":"text\/x-haskell","haxe":"text\/x-haxe","html4strict":"htmlmixed","java":"text\/x-java","java5":"text\/x-java","jquery":"javascript","mirc":"mirc","mysql":"sql","ocaml":"text\/x-ocaml","pascal":"text\/x-pascal","perl":"perl","perl6":"perl","plsql":"sql","properties":"text\/x-properties","q":"text\/x-q","scala":"scala","scheme":"text\/x-scheme","tcl":"text\/x-tcl","vb":"text\/x-vb","verilog":"text\/x-verilog","yaml":"text\/x-yaml","z80":"text\/x-z80"}