Ejemplo n.º 1
0
int main() {
	HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
	if (SUCCEEDED(hr)) {
		IPingable * ptrPingable;
		HRESULT hr = CoCreateInstance(CLSID_CoPingEngine, NULL, CLSCTX_LOCAL_SERVER, IID_IPingable, reinterpret_cast<void**>(&ptrPingable));
		if (SUCCEEDED(hr)) {
			ptrPingable->Initialize();

			StatusResponse status;
			ptrPingable->Ping(12345, &status);
			printf("Status for ping code 12345: %d %S\n", status.Code, status.Description);
			ptrPingable->Ping(777, &status);
			printf("Status for ping code 777: %d %S\n", status.Code, status.Description);
			ptrPingable->Ping(1800, &status);
			printf("Status for ping code 1800: %d %S\n", status.Code, status.Description);

			CComVariant history;
			hr = ptrPingable->RetrieveHistory(&history);

			if (SUCCEEDED(hr)) {
				printHistory(history);
			}
			else {
				DisplayStatus(TEXT("RetrieveHistory failed: \n"), hr);
			}

			// Try creating a larger history
			printf("Sending more pings...\n");
			for (int i = 0; i < 16; i++) {
				ptrPingable->Ping(i, &status);
			}

			hr = ptrPingable->RetrieveHistory(&history);

			if (SUCCEEDED(hr)) {
				printHistory(history);
			}
			else {
				DisplayStatus(TEXT("RetrieveHistory failed: \n"), hr);
			}

			SysFreeString(status.Description);
			ptrPingable->Release();
		}
		else {
			DisplayStatus(TEXT("CoCreateInstance(CoPingEngine) failed: "), hr);
		}
		CoUninitialize();
	}
	else {
		DisplayStatus(TEXT("CoInitializeEx failed: "), hr);
	}


	return 0;
}
Ejemplo n.º 2
0
//this function does what's needed for each built-in command. Note: these commands cannot be
//run in the background. Returns 1 if a built-in command is detected, 0 if not
int builtInCmd(char *argList[], struct hist *histList, int count) {

	int cdCheck;
	int isBuiltIn = 1;

	//builtin exit command
	if (strcmp(argList[0], "exit") == 0) {
		printf("Exiting shell...\n\n");
		exit(0);
	//builtin cd (change directory) command, implemented with chdir() system call
	} else if (strcmp(argList[0], "cd") == 0) {
		if ((cdCheck = chdir(argList[1]) == -1)) {
			printf("chdir() failure... now exiting shell");
			_exit(EXIT_FAILURE);
		}
	//builtin command to display history
	} else if (strcmp(argList[0], "history") == 0) {
		printHistory(&histList[0], count);
	//builtin command to display currently running jobs
	} else if (strcmp(argList[0], "jobs") == 0) {
		updateJobs();
		printJobs();
	//builtin command to bring a background job to the foreground
	} else if (strcmp(argList[0], "fg") == 0) {
		if (argList[1] == NULL)
			printf("Invalid command: must give a Process ID number with the fg command.\n");
		if (bringToForeground(argList) == 0)
			printf("The process with that PID is not currently running.\n");
	} else {
		isBuiltIn = 0;
	}
	return isBuiltIn;
}
Ejemplo n.º 3
0
int runCommand(){
	int i = 0;
	int argc = splitString(textBuffer, ' ');
	for(i =0;i<argc;i++){argv[i]=stringArray[i];}
	
	if(k_strcmp(argv[0], "")==0){}
	else if(k_strcmp(argv[0], "clear")==0){ clearScreen(); typeOffset = 0;}
	else if(k_strcmp(argv[0], "history")==0){ printHistory();}
	else if(k_strcmp(argv[0], "pong")==0){ pong();}
	else if(k_strcmp(argv[0], "help")==0){ listCommands();}
	else if(k_strcmp(argv[0], "welcome")==0){ welcome();}
	else if(k_strcmp(argv[0], "splash")==0){ splash();}
	else if(k_strcmp(argv[0], "ls")==0){ ls(argc, argv); }
	else if(k_strcmp(argv[0], "cat")==0){ cat(argc, argv); }
	else if(k_strcmp(argv[0], "rm")==0){ rm(argc, argv); }
	else if(k_strcmp(argv[0], "chmod")==0){ chmod(argc, argv); }
	else if(k_strcmp(argv[0], "te")==0){ te(argc, argv); }
	else if(k_strcmp(argv[0], "cp")==0){ cp(argc, argv); }
	else if(k_strcmp(argv[0], "diff")==0){ diff(argc, argv); }
	else if(k_strcmp(argv[0], "wc")==0){ wc(argc, argv); }
	else if(k_strcmp(argv[0], "su")==0){ su(argc, argv); }
	else if(k_strcmp(argv[0], "chown")==0){ chown(argc, argv); }
	else if(k_strcmp(argv[0], "echo")==0){ echo(argc, argv); }
	else if(k_strcmp(argv[0], "adduser")==0){ adduser(argc, argv); }
	else if(k_strcmp(argv[0], "deluser")==0){ deluser(argc, argv); }
	else if(k_strcmp(argv[0], "listus")==0){ listus(); }
	else if(k_strcmp(argv[0], "passwd")==0){ passwd(argc, argv); }

	else if(k_strcmp(argv[0], "mkdir")==0){ mkdir(argc, argv); }
	else if(k_strcmp(argv[0], "rmdir")==0){ rmdir(argc, argv); }
	else if(k_strcmp(argv[0], "cd")==0){ cd(argc, argv); }
	else if(k_strcmp(argv[0], "pwd")==0){ pwd(argc, argv); }
	else if(k_strcmp(argv[0], "mv")==0){ mv(argc, argv); }

	// else check files
	else {
		printToConsole("Error: Unknown command '");
		printToConsole(argv[0]);
		printToConsole("'\n");
	}

	return 0;
}
Ejemplo n.º 4
0
/* sig_handler called asyncronously by the OS.  This function prints
 * the recieved signal to standard output.  Special cases for SIGINT,
 * print out command history, and SIGCHLD, handles termination of a child
 * process are included.
 * 		Parameters:
 *			int sig - signal number to be handled.
 */
void sig_handler(int sig) {
	int status;
	pid_t pid;
	
	if(sig == SIGINT) {
		printHistory();
	}
	else if(sig == SIGCHLD) {
		while( (pid = waitpid(-1, &status, WNOHANG)) > 0 ) {
 			removeChild(pid);
		}
	}
	else {
		printf("\nRecieved Signal:%i\n", sig);
	}
	
	// normal execution has been inturrupted.
	interrupted = 1;
}
Ejemplo n.º 5
0
void printHistoryList()
{
	int dif = (*HISTORY).size - HISTCOUNT;
	int i = 1;

	Node * cur = (*HISTORY).head;

	while(i <= dif)
	{
		cur = (*cur).next;
		i++;
	}

	while((*cur).next != NULL)
	{
		cur = (*cur).next;
		printf("%d ", i);
		printHistory((*cur).data);
		i++;
	}
}
Ejemplo n.º 6
0
int main()
{

 char input[1000];
 char history[999][1000]; 
 // char history[4][1000]; 
 int historyPointerLocation = 0;
 int noOfElementsInHistory = 0;
 while(1)
 {
 	// signal(SIGCHLD, SIG_DFL);
 	printf("\nSamShell-v0.0> ");
 	
 	
 	fgets(input,1000,stdin);
 	char* input2 = removeWhiteSpace(input);
 	
 	strcpy(input,input2);
 	char inputArray[100][100];
 	int inputArrayCount = 0,i=0;

 	splitCommandAndArgs(input,&inputArrayCount,inputArray);

 	if(input[0]=='\0')
 	{
 		continue;
 	}

 	int redirectQ = searchForRedirection(inputArray,&inputArrayCount);
 	if(redirectQ!=0)
 	{
 		redirectionExecution(input, inputArray,&inputArrayCount,&redirectQ);
		int i=0;
 		for(;i<inputArrayCount;i++)
 		{
 			strcat(input," ");
 			strcat(input,inputArray[i]);
 		}
	 	if(historyPointerLocation>998){historyPointerLocation=0;}
		strcpy(history[historyPointerLocation],input);
		historyPointerLocation=historyPointerLocation + 1;
		if(noOfElementsInHistory!=999)
		{
			noOfElementsInHistory = noOfElementsInHistory+1;
		}
 		continue;
 	}

 	int pipeQ = searchForPiping(inputArray,&inputArrayCount);
 	if(pipeQ==1)
 	{
 		pipingExecution(input,inputArray,&inputArrayCount);
 		int i=0;
 		for(;i<inputArrayCount;i++)
 		{
 			strcat(input," ");
 			strcat(input,inputArray[i]);
 		}
	 	if(historyPointerLocation>998){historyPointerLocation=0;}
		strcpy(history[historyPointerLocation],input);
		historyPointerLocation=historyPointerLocation + 1;
		if(noOfElementsInHistory!=999)
		{
			noOfElementsInHistory = noOfElementsInHistory+1;
		}
 		continue;
 	}
 	if((strlen(input))==4)
 	{
 		char temporary[1000];
 		strcpy(temporary,input);
 		int i=0;
 		for(;i<strlen(temporary);i++)
 		{
 			temporary[i] = tolower(temporary[i]);
 		}
	 	if(strncmp(temporary,EXIT,4)==0 || strncmp(temporary,QUIT,4)==0 )
	 	{
	 		printf("\n");
	 		printf(BYE);
	 		printf("\n");
	 		return EXIT_SUCCESS;
	 	}
	 	if(input[0]=='!')
	 	{
	 		if(isdigit(input[1])&&isdigit(input[2])&&isdigit(input[3]))
	 		{
	 			int hundreds = (input[1] - '0')*100;
	 			int tens = (input[2] - '0')*10;
	 			int ones = (input[3] - '0');
	 			int calculatedNumber = hundreds + tens + ones;
	 			if(calculatedNumber>noOfElementsInHistory || calculatedNumber==0)
	 			{
	 				fprintf(stderr,"SamShell: ERROR : '%s': event not found\n",input);
	 				continue;
	 			}
	 			char* temp = searchHistoryUsingNumber(calculatedNumber,&historyPointerLocation,&noOfElementsInHistory,history);
	 			strcpy(input,temp);
	 			splitCommandAndArgs(input,&inputArrayCount,inputArray);
	 			if(strlen(input)==7)
 				{
		 			if(strncmp(input,HISTORY,7)==0)
		 			{
		 			printHistory(history,&historyPointerLocation,&noOfElementsInHistory);
		 			if(historyPointerLocation>998){historyPointerLocation=0;}
			 		strcpy(history[historyPointerLocation],input);
			 		historyPointerLocation=historyPointerLocation + 1;
			 		if(noOfElementsInHistory!=999)
			 		{
			 			noOfElementsInHistory = noOfElementsInHistory+1;
			 		}
		 			 continue;
		 			}
 				}

 				int redirectQIn = searchForRedirection(inputArray,&inputArrayCount);
			 	if(redirectQIn!=0)
			 	{
			 		redirectionExecution(input, inputArray,&inputArrayCount,&redirectQIn);
					int i=0;
			 		for(;i<inputArrayCount;i++)
			 		{
			 			strcat(input," ");
			 			strcat(input,inputArray[i]);
			 		}
		 			if(historyPointerLocation>998){historyPointerLocation=0;}
			 		strcpy(history[historyPointerLocation],input);
			 		historyPointerLocation=historyPointerLocation + 1;
			 		if(noOfElementsInHistory!=999)
			 		{
			 			noOfElementsInHistory = noOfElementsInHistory+1;
			 		}
			 		continue;
			 	}

			 	int pipeQIn = searchForPiping(inputArray,&inputArrayCount);
			 	if(pipeQIn==1)
			 	{
			 		pipingExecution(input,inputArray,&inputArrayCount);
			 		int i=0;
			 		for(;i<inputArrayCount;i++)
			 		{
			 			strcat(input," ");
			 			strcat(input,inputArray[i]);
			 		}
		 			if(historyPointerLocation>998){historyPointerLocation=0;}
			 		strcpy(history[historyPointerLocation],input);
			 		historyPointerLocation=historyPointerLocation + 1;
			 		if(noOfElementsInHistory!=999)
			 		{
			 			noOfElementsInHistory = noOfElementsInHistory+1;
			 		}
			 		continue;
			 	}

			 	if((strlen(input))==2)
			 	{
			 		if(strncmp(input,"cd",2)==0)
			 		{
			 			if(inputArrayCount>=1)
			 			{
			 			 changeDirForeFunction(input,inputArray[0]);
			 			}
			 			else
			 			{
			 			 fprintf(stderr,"SamShell: ERROR : invalid argument for cd\n");
			 			}
			 			int i=0;
				 		for(;i<inputArrayCount;i++)
				 		{
				 			strcat(input," ");
				 			strcat(input,inputArray[i]);
				 		}
			 			if(historyPointerLocation>998){historyPointerLocation=0;}
				 		strcpy(history[historyPointerLocation],input);
				 		historyPointerLocation=historyPointerLocation + 1;
				 		if(noOfElementsInHistory!=999)
				 		{
				 			noOfElementsInHistory = noOfElementsInHistory+1;
				 		}
						   continue;
			 		}
 				}

	 			searchInMyPath(input,inputArray,inputArrayCount);
	 			continue;
	 		}
	 		else
	 		{
	 			
	 			searchInMyPath(input,inputArray,inputArrayCount);
	 			continue;
	 		}
	 	}
 	}	

 	if((strlen(input))==2)
 	{
 		if(strncmp(input,"cd",2)==0)
 		{
 			if(inputArrayCount>=1)
 			{
 			 changeDirForeFunction(input,inputArray[0]);
 			}
 			else
 			{
 			 fprintf(stderr,"SamShell: ERROR : invalid argument for cd\n");
 			}
 			int i=0;
	 		for(;i<inputArrayCount;i++)
	 		{
	 			strcat(input," ");
	 			strcat(input,inputArray[i]);
	 		} 			
 			if(historyPointerLocation>998){historyPointerLocation=0;}
	 		strcpy(history[historyPointerLocation],input);
	 		historyPointerLocation=historyPointerLocation + 1;
	 		if(noOfElementsInHistory!=999)
	 		{
	 			noOfElementsInHistory = noOfElementsInHistory+1;
	 		}
			continue;
 		}
 	}

 	if((strlen(input))==2)
 	{
 		
 		if(input[0]=='!' && input[1]=='!')
 		{
 			if(noOfElementsInHistory!=0)
 			{
 				char* temp;
 				if(historyPointerLocation!=0)
 				{
 					temp = history[historyPointerLocation-1];
 				}
 				else
 				{
 					temp = history[noOfElementsInHistory-1];
 				}
	 			strcpy(input,temp);
	 			splitCommandAndArgs(input,&inputArrayCount,inputArray);

	 			if(strncmp(input,HISTORY,7)==0)
	 			{
	 				printHistory(history,&historyPointerLocation,&noOfElementsInHistory);
	 				continue;
	 			}

	 			int redirectQIn = searchForRedirection(inputArray,&inputArrayCount);
			 	if(redirectQIn!=0)
			 	{
			 		redirectionExecution(input, inputArray,&inputArrayCount,&redirectQIn);
					int i=0;
			 		for(;i<inputArrayCount;i++)
			 		{
			 			strcat(input," ");
			 			strcat(input,inputArray[i]);
			 		}
			 		strcpy(history[historyPointerLocation],input);
			 		historyPointerLocation=historyPointerLocation + 1;
			 		if(noOfElementsInHistory!=4)
			 		{
			 			noOfElementsInHistory = noOfElementsInHistory+1;
			 		}
			 		continue;
			 	}

			 	int pipeQIn = searchForPiping(inputArray,&inputArrayCount);
			 	if(pipeQIn==1)
			 	{
			 		pipingExecution(input,inputArray,&inputArrayCount);
			 		int i=0;
			 		for(;i<inputArrayCount;i++)
			 		{
			 			strcat(input," ");
			 			strcat(input,inputArray[i]);
			 		}

			 		continue;
			 	}

			 	if((strlen(input))==2)
			 	{
			 		if(strncmp(input,"cd",2)==0)
			 		{
			 			if(inputArrayCount>=1)
			 			{
			 			 changeDirForeFunction(input,inputArray[0]);
			 			}
			 			else
			 			{
			 			 fprintf(stderr,"SamShell: ERROR : invalid argument for cd\n");
			 			}
			 			int i=0;
				 		for(;i<inputArrayCount;i++)
				 		{
				 			strcat(input," ");
				 			strcat(input,inputArray[i]);
				 		}
				 		if(historyPointerLocation>998){historyPointerLocation=0;}
				 		strcpy(history[historyPointerLocation],input);
				 		historyPointerLocation=historyPointerLocation + 1;
				 		if(noOfElementsInHistory!=999)
				 		{
				 			noOfElementsInHistory = noOfElementsInHistory+1;
				 		}
						continue;
			 		}
 				}
	 			searchInMyPath(input,inputArray,inputArrayCount);
	 			continue;
 			}
 			else
 			{
 				fprintf(stderr,"SamShell: ERROR : '%s': event not found\n",input);
 				continue;
 			}
 		}
 	}

 	if(input[0]=='!')
 	{
 		int i=1;
 		char *tempo;
 		char prefixString[1000];
 		tempo = strndup(input+1,strlen(input)-1);
 		strcpy(prefixString,tempo);
 		for(i=0;i<inputArrayCount;i++)
 		{
 			strcat(prefixString," ");
 			strcat(prefixString,inputArray[i]);
 		}
 		prefixString[strlen(prefixString)] = '\0';
 		char *temp = searchHistoryUsingPrefix(prefixString,&historyPointerLocation,&noOfElementsInHistory,history);
 		if(temp[0]!='\0')
 		{
 			printf("\ntemp %s\n",temp);
 			strcpy(input,temp);
 			splitCommandAndArgs(input,&inputArrayCount,inputArray);



 			if(strncmp(input,HISTORY,7)==0)
	 			{
	 				printHistory(history,&historyPointerLocation,&noOfElementsInHistory);
	 				continue;
	 			}

	 			int redirectQIn = searchForRedirection(inputArray,&inputArrayCount);
			 	if(redirectQIn!=0)
			 	{
			 		redirectionExecution(input, inputArray,&inputArrayCount,&redirectQIn);
					int i=0;
			 		for(;i<inputArrayCount;i++)
			 		{
			 			strcat(input," ");
			 			strcat(input,inputArray[i]);
			 		}
			 		if(historyPointerLocation>998){historyPointerLocation=0;}
			 		strcpy(history[historyPointerLocation],input);
			 		historyPointerLocation=historyPointerLocation + 1;
			 		if(noOfElementsInHistory!=999)
			 		{
			 			noOfElementsInHistory = noOfElementsInHistory+1;
			 		}
			 		continue;
			 	}

			 	int pipeQIn = searchForPiping(inputArray,&inputArrayCount);
			 	if(pipeQIn==1)
			 	{
			 		pipingExecution(input,inputArray,&inputArrayCount);
			 		int i=0;
			 		for(;i<inputArrayCount;i++)
			 		{
			 			strcat(input," ");
			 			strcat(input,inputArray[i]);
			 		}
			 		if(historyPointerLocation>998){historyPointerLocation=0;}
			 		strcpy(history[historyPointerLocation],input);
			 		historyPointerLocation=historyPointerLocation + 1;
			 		if(noOfElementsInHistory!=999)
			 		{
			 			noOfElementsInHistory = noOfElementsInHistory+1;
			 		}
			 		continue;
			 	}

			 	if((strlen(input))==2)
			 	{
			 		if(strncmp(input,"cd",2)==0)
			 		{
			 			if(inputArrayCount>=1)
			 			{
			 			 changeDirForeFunction(input,inputArray[0]);
			 			}
			 			else
			 			{
			 			 fprintf(stderr,"SamShell: ERROR : invalid argument for cd\n");
			 			}
			 			int i=0;
				 		for(;i<inputArrayCount;i++)
				 		{
				 			strcat(input," ");
				 			strcat(input,inputArray[i]);
				 		}
				 		if(historyPointerLocation>998){historyPointerLocation=0;}
				 		strcpy(history[historyPointerLocation],input);
				 		historyPointerLocation=historyPointerLocation + 1;
				 		if(noOfElementsInHistory!=999)
				 		{
				 			noOfElementsInHistory = noOfElementsInHistory+1;
				 		}
						continue;
			 		}
 				}
	 			searchInMyPath(input,inputArray,inputArrayCount);
	 			continue;
 		}
 		
 	}

 	if(strncmp(input,HISTORY,7)!=0)
	{
 	 searchInMyPath(input,inputArray,inputArrayCount);
 	}

 	if(historyPointerLocation>998){historyPointerLocation=0;}
 	if(inputArrayCount!=0)
 	{
 		for(i=0;i<inputArrayCount;i++)
 		{
 			strcat(input," ");
 			strcat(input,inputArray[i]);
 		}
 	}
 	strcpy(history[historyPointerLocation],input);
 		
 	historyPointerLocation=historyPointerLocation + 1;
    if(noOfElementsInHistory!=999)
 	{
 		noOfElementsInHistory = noOfElementsInHistory+1;
 	}
 	if(strlen(input)==7)
 	{
	 	if(strncmp(input,HISTORY,7)==0)
	 	{
	 		printHistory(history,&historyPointerLocation,&noOfElementsInHistory);
	 		continue;
	 	}
 	}

 	
	
 }
 return EXIT_SUCCESS;
 
}
Ejemplo n.º 7
0
int main(int argc, char * argv[], char **envp)
{
    //The following two functions catch and process the interrupt and stop signals
    //AKA signals sent by the Ctrl-C and Ctrl-Z commands
    if (signal(SIGINT,signal_catcher)==SIG_ERR)
    {
        perror("Sigset cannot set SIGINT");
        exit(SIGINT);
    }
    if (signal(SIGTSTP, signal_catcher)==SIG_ERR)
    {
        perror("Sigset can not set SIGTSTP");
        exit(SIGTSTP);
    }
    
    //Declaring and initializing variables to be used later
    initHistory();
    initAlias();
    int this_input = 0;
    
    char * input = (char *) malloc(sizeof(char)*64);
    strcpy (input, "noexit");
    char *shellname = (char *) malloc(sizeof(char)*32);
    strcpy (shellname, "myshell");
    
    setShellName(shellname);
    
    printf ("[%s]%% ", shellname);
    input = getLine(input, 100);
    
    //Making sure the program does not crash if the input simply the return key
    while (strcmp(input,"\0") == 0)
    {
        printf ("[%s]%% ", shellname);
        input = getLine(input, 100);
    }
    
    setHistory(input);
    breakLine (input);
    this_input = whichInput();
    
    char ** argrv = getargrv();
    int argrc = getargrc();
    
    int loop = 1;
    
    while (loop != 0)
    {
        //Loop and process commands until the exist command is entered
        if(this_input==4) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                //printf("Before forking PID:%d\n", getpid());
                int pid = fork();
                if(pid==0)
                {
                    //sleep(2); //putting a delay in to emphasize background process
                    //printf("\nchild PID: %d\n", getpid());
                    decrargrc();
                    list();
                    //printf("\nIn the child process - ended.\n\n");
                    return 0;
                } else
                {
                    //printf("PPID:%d\n", getpid());
                    //printf("In the parent process.\n");
                    printf("%s process running in background", argrv[0]);
                }
            } else
                list();
            
        } else if(this_input==3) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    decrargrc();
                    pwd();
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
                pwd();
        } else if(this_input==6) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    decrargrc();
                    prompt();
                    shellname = getShellName();
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
            {
                prompt();
                shellname = getShellName();
            }
        } else if(this_input==2) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    decrargrc();
                    dirChange();
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
                dirChange();
        } else if(this_input==5) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    decrargrc();
                    mypid();
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
                mypid();
        } else if(this_input==1) {
            if (getargrc() == 1)
            {
                loop = 0;
                free (input);
                free (shellname);
                
                input = NULL;
                shellname = NULL;
                
                freeDynamicMem();
                return 0;
            } else {
                printf("%s: Arguments not valid.", argrv[0]);
            }
        } else if(this_input==7) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    decrargrc();
                    printHistory();
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
                printHistory();
        } else if(this_input==8) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    printf("\n***I've put a 3 second delay in to emphasize this background process\n");
                    sleep(3); //putting a delay in to emphasize background proces
                    decrargrc();
                    printEnv(envp);
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
                printEnv(envp);
        }else if(this_input==9) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    decrargrc();
                    alias();
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
                alias();
        }else if(this_input==10) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    decrargrc();
                    murder();
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
                murder();
        }else {
            nocmd(input);
        }
        printf ("\n[%s]%% ", shellname);
        input = getLine(input, 100);
        while (strcmp(input,"\0") == 0)
        {
            printf ("[%s]%% ", shellname);
            input = getLine(input, 100);
        }
        setHistory(input);
        breakLine (input);
        this_input = whichInput();
        argrv = getargrv();
        argrc = getargrc();
    }
    return 0;
}
Ejemplo n.º 8
0
//---------------------------------------------------------------------
//---------------------------------------------------------------------
//---------------------------------------------------------------------
int 
main(int argc, char *argv[]) 
{
  extern char *optarg;
  int    optInd   = 0;
  char   optChar  = 0;  

  static struct option optLong[] = {
    { "database"   , 1 , 0           , 'D' },
    { "path"       , 1 , 0           , 'p' },
    { "time"       , 1 , 0           , 't' },
    { "expiration" , 1 , 0           , 'x' },
    { "flavor"     , 1 , 0           , 'F' },
    { "file"       , 1 , 0           , 'f' },
    { "get"        , 0 , (int *)&action ,  GetDB  },
    { "read"       , 0 , (int *)&action ,  GetDB  },
    { "set"        , 0 , (int *)&action ,  SetDB  },
    { "write"      , 0 , (int *)&action ,  SetDB  },
    { "tree"       , 0 , (int *)&action ,  PrintTree },
    { "history"    , 0 , (int *)&action ,  PrintHistory },
    { "config"     , 0 , (int *)&action ,  PrintConfig },
    { "comment"    , 1 , 0              , 'c' },
    { "verbose"    , 0 , &verboseMode   , true},
    { "quiet"      , 0 , &verboseMode   , false},
    { "dataonly"   , 0 , &dataOnlyMode  , true},
    { "debug"      , 0 , &debugMode     , true},
    { "help"       , 0 , 0              , 'h' },
    { 0, 0, 0, 0}
  };


  //   cout << indexFromString("05TB01" )  << endl;
  //   cout << indexFromString("P05TB01")  << endl;
  //   cout << indexFromString("05P1" ,kEEmcMaxSect*kEEmcMaxBox)  << endl;
  //   cout << indexFromString("E05TB",kEEmcMaxSect*kEEmcMaxBox)  << endl;
  //   cout << indexFromString("12TB13" )  << endl;
  //   cout << indexFromString("V12TB13")  << endl;
  //   cout << indexFromString("13TG"  ,kEEmcMaxSect*kEEmcMaxBox) << endl;
  //   cout << indexFromString("A13TG" ,kEEmcMaxSect*kEEmcMaxBox) << endl;
  //   exit(0);

  // arguments and init
  argv0 = strrchr(argv[0],'/');
  argv0 = ( argv0 == NULL )  ? argv[0] : ++argv0 ;

  while((optChar = getopt_long(argc,argv,"D:p:t:x:F:f:c:grswTHCdvqh",optLong,&optInd)) != EOF) {
    switch(optChar) {
    case  0  : break;
    case 'D' : dbName      = optarg;       break;
    case 'p' : dbPath      = optarg;       break;
    case 't' : dbTime      = optarg;       break;
    case 'x' : dbExpTime   = optarg;       break;
    case 'F' : dbFlavor    = optarg;       break; 
    case 'f' : dbFile      = optarg;       break; 
    case 'r' : // same as g
    case 'g' : action      = GetDB;        break;
    case 'w' : // same as s
    case 's' : action      = SetDB;        break;
    case 'T' : action      = PrintTree;    break;
    case 'H' : action      = PrintHistory; break;
    case 'C' : action      = PrintConfig;  break;
    case 'c' : dbComment   = optarg;       break;  
    case 'd' : dataOnlyMode= true;         break;
    case 'v' : verboseMode = true;         break;
    case 'q' : quietMode   = true;         break;
    case 'h' : usage(); return(0);         break;
    default  : usage("unknown option");    break;
    };
  }
  if(!dbPath  && action!=PrintConfig ) usage("database path missing");


  // 
  StDbManager    *mgr    = StDbManager::Instance();
  StDbConfigNode *dbNode = NULL;
  StDbTable      *dbTab  = NULL;
  char           *node   = NULL;
  FILE           *file   = NULL;

  mgr->setVerbose(verboseMode);
  mgr->setQuiet(quietMode);

  // sanity check 
  if( ! mgr->findDefaultServer() ) {
    fprintf(stderr,"cannot find the default DB server\n");
    return(-1);
  }

  if(dbFile) { 
    file = fopen(dbFile,(action==SetDB) ? "r" : "w");
    if(!file) { 
      fprintf(stderr,"%s: fopen '%s' failed, %s\n",argv0,dbFile,strerror(errno)); 
      return(-1); 
    }
  } else {
    file = (action==SetDB) ? stdin : stdout;
  }

  switch(action) {
  case PrintTree:
    node   = node=strsep(&dbPath,"/");
    if(node) { 
      dbNode = mgr->initConfig(dbName,node);
      if(dbNode) { 
	if(verboseMode || !quietMode) 
	  fprintf  (file,"DATABASE TREE:\n");
	fprintf  (file,"%s/\n",node);
	if(printTree(file,dbNode)<=0) {
	  fprintf  (stderr,"config %s is empty\n",node);
	}
      }
    }
    return 0;
    break;
  case PrintConfig:
    if(verboseMode || !quietMode) 
     fprintf(file,"DATABASE VERSIONS:\n");
    printConfig(file,mgr);
    return 0;
  default:
    break;
  }


  // parse database path 
  char *preNode="";
  while( (node=strsep(&dbPath,"/")) != NULL ) {
    StDbConfigNode *tn = (dbNode==NULL) ? 
      mgr->initConfig(dbName,node) : dbNode->findConfigNode(node);
    if(!tn) break; // assume the last token is a db table
    dbNode = tn;
    printf("found database node: %s\n",node);
    preNode=node;
  }

  if(!node) usage("invalid path");

  dbTab = dbNode->findTable(node);
  if(!dbTab) { fprintf(stderr,"%s: table %s not found\n",argv0,node); return (-1); }

  dprintf("found table: %s\n",node);

  int nrows=dbTab->GetNRows();
  int ndata=0;
  
  EEmcDbIOBase *dbIO = getDbIO(preNode,node,nrows);
  if(dbIO==NULL) return(-1);

  char keyLine[EEmcDbMaxDbPathLen];
  //char keyFile[EEmcDbMaxKeyLength];
  char keyBase[EEmcDbMaxKeyLength];
  time_t tUnix    =                     getTimeStamp(dbTimeFormat,dbTime);
  time_t tExpUnix = (dbExpTime!=NULL) ? getTimeStamp(dbTimeFormat,dbExpTime) : 0;

  dbTab->setFlavor(dbFlavor);
  switch(action) {
  case PrintHistory:
    printHistory(file,mgr,dbTab,dbIO); 
    return 0; 
    break;
  case SetDB:
    fgets (keyLine,EEmcDbMaxDbPathLen-1,file);
    sprintf(keyBase,EEmcDbKeyFormat,dbNode->printName(),node);
    printf("AAA=%s=\n",keyBase);
    if(strstr(keyLine,keyBase)==0 &&  strcmp(keyLine,keyToEverything) ) {
      fprintf(stderr,"signature mismatch: data file key '%s', required '%s'\n",
	      keyLine,keyBase);
      return (-1);
    }

    dbIO->setComment(dbComment);

    ndata = dbIO->read(file);
    if(ndata<=0) {
      fprintf(stderr,"%s: reading file %s failed\n",argv0,dbFile);
      return(-1);
    }
    if(nrows>1) { 
      dbTab->SetTable(dbIO->getData(),ndata, dbIO->getIndices());
    } else {
      dbTab->SetTable(dbIO->getData(),ndata);
    }
    if(tExpUnix>0) { 
      dbTab->setEndStoreTime(tExpUnix);
      fprintf(stderr,"%s: setting end time %ld\n",argv0,tExpUnix);
    }

    //mgr->setStoreTime(getTimeStamp(dbTimeFormat,dbTime));
    mgr->setStoreTime(tUnix);
    if(! mgr->storeDbTable(dbTab) ) {
      fprintf(stderr,"%s: storing table %s failed\n",argv0,node);
      return(-1);
    }
  
    break;
  case GetDB:
    mgr  ->setRequestTime(tUnix);
    if( ! mgr->fetchDbTable(dbTab) ) {
      fprintf(stderr,"%s: problem with fetch for time stamp %ld / %s",argv0,tUnix,ctime(&tUnix));
      fprintf(stderr," There is no record for this table over the time period :\n");
      fprintf(stderr," BeginDate     = %s\t",dbTab->getBeginDateTime());
      fprintf(stderr,"   EndDate     = %s\n",dbTab->getEndDateTime());
      fprintf(stderr," BeginTimeUnix = %d\t",dbTab->getBeginTime());
      fprintf(stderr,"   EndTimeUnix = %d\n",dbTab->getEndTime());
      return(-1);
    }
    if(! dbTab->GetTable() ) {
      fprintf(stderr,"no data found in table %s\n",node);
      return(-1);
    } 
    dbIO->setData(dbTab->GetTable());

    if(verboseMode || !quietMode)
    fprintf(stderr,"BNL Time Stamp Range  from: %s   to:    %s \n",
	    fmtSqlTime(dbTab->getBeginDateTime()),fmtSqlTime(dbTab->getEndDateTime()));
    if(!dataOnlyMode) {
      fprintf(file,EEmcDbKeyFormat,dbNode->printName(),node);
      fprintf(file,"\n");
    }
    ndata     = dbIO->write(file);
    dbComment = dbIO->getComment();
    if(verboseMode || !quietMode)
      fprintf(stderr,"COMMENT: %s\n",dbComment);
    break;
  default:
    break;
  } 

  if(ndata>0) {  
    dprintf("database access successful %d\n",ndata);
  } else { 
    fprintf(stderr,"%s: table %s access failed\n",argv0,node); 
  }
    

  fclose(file);
  return 0; 
} 
Ejemplo n.º 9
0
int main(int argc, char *argv[]){
  char *line;
  pipeline pl;
  int run;
  
  //flags
  int redo = 0;
  int skip = 0;
  int isResume = 0;
  
  char *promptstr;
  char* buffer;
  numExits = 0;
  jobIndex = 0;
  histIndex = 0;
  back = 0;
  script = 0;
  
  FILE* in;
  /* check for the right number of arguments */
  //if ( argc > 2 ) {
  //  printusage(argv[0]);
  //  exit(-1);
  //}
  if (argc >= 2)
  {
  	DIR* dirp;
	struct dirent *dp;
	int isFound = 0;
	if ((dirp = opendir(".")) == NULL) 
        {
        	perror("couldn't open path");
                return 0;
        }
        
        //put files into array and sort their names
        while ((dp = readdir(dirp)) != NULL)
	{
		if (strcmp(dp->d_name, argv[1]) == 0)
		{
			isFound = 1;
		}
	}
	if (isFound == 0)
	{
		printf("%s: Command not found\n", argv[1]);
	}
	else
	{
		in = fopen(argv[1], "r");
		buffer = (char*)malloc(sizeof(in));
		script = 1;
	}
  }
  //struct termios saved_term_mode; 
  struct sigaction action;
  action.sa_handler = killHandle;     /* set tick to be the handler function */
  sigemptyset(&action.sa_mask); /* clear out masked functions */
  action.sa_flags   = 0;        /* no special handling */
  
  struct sigaction action2;
  action2.sa_handler = susHandle;     /* set tick to be the handler function */
  sigemptyset(&action2.sa_mask); /* clear out masked functions */
  action2.sa_flags   = 0;        /* no special handling */

    /*
     * Use the sigaction function to associate the signal action with SIGALRM.
     */
    if (sigaction(SIGINT, &action, NULL) < 0 ) {
        fprintf(stderr, "SIGINT\n");
        exit(-1);
    }
    
    if(sigaction(SIGTSTP, &action2, NULL) < 0) {
    	fprintf(stderr, "SIGTSTP\n");
        exit(-1);
    }
    //saved_term_mode = set_raw_term_mode();
	initHistory();
	initJobs();
	//strcpy(jobs[1], "hey");
  /* set prompt */
  promptstr = PROMPT;

  run = TRUE;
  if (script == 0)
  	prompt(promptstr);
  while ( run ) 
  {
    /// if reexecute was not called
    if (redo == 0)
    {
    	if (script == 0)
    	{
	    if ( NULL == (line = readLongString(stdin)) ) 
	    {
	      if ( feof(stdin) )
	        run = FALSE;
	    } 
	}
	else
	{
		fgets(line, sizeof(in), in);
		if (line[0] == '%')
		{
			line++;
			isResume = 1;
		}
	}
	
    }
    else
    {
    	//printf("histInd: %d\n", histIndex);
    	///if reexecute was called,
    	///find the correct place in the history
    	///list to extract the reexecuted command
    	int temp = histIndex;
    	temp--;
    	int ind = 0;
    	while (ind != reNumber)
    	{
    		temp--;
    		ind++;
    	}
    	line = history[temp];
    	printf("%s\n", line);
    }
    if (line == NULL)
    {
	    if (feof(stdin))
        run = FALSE;
    }
    else 
    {
    	if (line[0] == '%')
	{
		line++;
		isResume = 1;
	}
      /* We got a line, send it off to the pipeline cracker and
       * launch it
       */
       //if (redo == 0)
       //{
       	  pl = crack_pipeline(line);     	  
       //}
	redo = 0;
      /*
       * Show that it worked.  This is where you're going to do
       * something radically different: rather than printing the
       * pipeline, you're going to execute it.
       */
       
      if ( pl != NULL && strlen(pl->cline) > 0) 
      {
      	/*
      	if (pl->cline[0] == '%')
        {
        	int i;
        	isResume = 1;
        	pl->stage[0].argv[0][0] = ' ';
        	for (i = 0; i < strlen(pl->cline)-1; i++)
        	{
        		pl->stage[0].argv[0][i] = pl->stage[0].argv[0][i+1];
        	}
        	pl->stage[0].argv[0][strlen(pl->cline)-1] = '\0';
        }
        
        */
        //print_pipeline(stdout,pl); /* print it. */
        addHistory(pl->cline);
        
        ///add to the history what was typed into the command line
        if (strcmp(pl->stage[0].argv[0], "history") == 0)
        {
        	///print the history if possible
        	if (pl->stage[0].argc > 1)
        	{
        		printf("Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits = 0;
        	if (skip == 0)
        		printHistory();
        	skip = 0;
        }
        else if (strcmp(pl->stage[0].argv[0], "jobs") == 0)
        {
        	///print the suspended jobs if possible
        	if (pl->stage[0].argc > 1)
        	{
        		printf("Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits = 0;
        	if (skip == 0)
        		printJobs();
        	skip = 0;
        }
        else if (strcmp(pl->stage[0].argv[0], "exit") == 0)
        {
        	///exit vssh if possible
        	if (pl->stage[0].argc > 1)
        	{
        		fprintf(stderr, "Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits++;
        	if (skip == 0)
        		exitCmd();
        	skip = 0;
        }
        else if (strcmp(pl->stage[0].argv[0], "bg") == 0)
        {
        	///background the most recently suspended job if possible
        	if (pl->stage[0].argc > 1)
        	{
        		fprintf(stderr, "Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits = 0;
        	if (skip == 0)
        		bg(jobs[jobIndex-1]);
        	skip  = 0;
        }
        else if (strcmp(pl->stage[0].argv[0], "fg") == 0)
        {
        	///foreground the most recently backgrounded job if possible
        	if (pl->stage[0].argc > 1)
        	{
        		fprintf(stderr, "Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits = 0;
        	if (skip == 0)
        		fg(jobs[jobIndex-1]);
        	skip = 0;
        }
        else if (strcmp(pl->stage[0].argv[0], "cd") == 0)
        {
        	///change the directory of vssh if possible
        	if (pl->stage[0].argc > 2)
        	{
        		fprintf(stderr, "Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits = 0;
        	if (skip == 0)
        		cd(pl->stage[0].argv[1]);
        	skip = 0;
        }
        else if (isResume == 1)
        {
        	///foreground the specified job if possible
        	if (pl->stage[0].argc > 1)
        	{
        		fprintf(stderr, "Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits = 0;
        	if (skip == 0)
        	{
        		//pl->stage[0].argv[0]++;
        		int i; 
        		int killFlag = 0;
        		for (i = 0; i < strlen(pl->stage[0].argv[0]); i++)
        		{
        			if (!isdigit(pl->stage[0].argv[0][i]))
        			{
        				///if the supplied job number is not a number
        				///then print error
        				killFlag = 1;
        				fprintf(stderr, "%s: No such job.\n", pl->stage[0].argv[0]);	
        			}
        		}
        		if (killFlag == 0)
        		{
        			if (atoi(pl->stage[0].argv[0]) <= 0 || atoi(pl->stage[0].argv[0]) > jobIndex)
        				///if the supplied job number is not a valid job index
        				///then print error
        				fprintf(stderr, "%s: No such job.\n", pl->stage[0].argv[0]);
        			else
        				resume(jobs[atoi(pl->stage[0].argv[0])-1]->id, atoi(pl->stage[0].argv[0])-1);
        		}
        	}
        	skip = 0;
        }
        else if (strcmp(pl->stage[0].argv[0], "!") == 0)
        {
        	///reexecute the specified history command if possible
        	if (pl->stage[0].argc > 2 || strlen(pl->stage[0].argv[1]) > 3)
        	{
        		fprintf(stderr, "Junk after built-in command\n");
        		skip = 1;
        	}
        	///if the number supplied is not a valid history index
        	///then print error
        	if (pl->stage[0].argv[1][0] == '0' && skip == 0)
        	{
        		fprintf(stderr, "%s: Event not found\n", pl->stage[0].argv[1]);
        		skip = 1;
        	}
        	if (strlen(history[atoi(pl->stage[0].argv[1])]) <= 0 && skip == 0)
		{
			fprintf(stderr, "%s: Event not found\n", pl->stage[0].argv[1]);
			skip = 1;
		}
        	int i;
        	for (i = 0; i < strlen(pl->stage[0].argv[1]); i++)
        	{
			if (!isdigit(pl->stage[0].argv[1][i]) && skip == 0)
			{
				///if the number supplied is not a number
        			///then print error
				fprintf(stderr, "%s: Event not found\n", pl->stage[0].argv[1]);
				skip = 1;
			}
		}
        	numExits = 0;
        	if (skip == 0)
        	{
        		redo = 1;
        		reNumber = atoi(pl->stage[0].argv[1]);
        		//printf("renum: %d\n", reNumber);
        		//pl = crack_pipeline(history[atoi(pl->stage[0].argv[1])]);
			//printf("%s\n", pl->cline);
			//lineno++;
        		//continue;
        	}
        	skip = 0;
        }
        else if (strcmp(pl->stage[0].argv[0], "kill") == 0)
        {
        	///kill the specified job if possible
        	if (pl->stage[0].argc > 2)
        	{
        		fprintf(stderr, "Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits = 0;
        	if (skip == 0)
        	{
        		int i; 
        		int killFlag = 0;
        		for (i = 0; i < strlen(pl->stage[0].argv[1]); i++)
        		{
        			///if the supplied job number is not a number
        			///then print error
        			if (!isdigit(pl->stage[0].argv[1][i]))
        			{
        				killFlag = 1;
        				fprintf(stderr, "%s: No such job.\n", pl->stage[0].argv[1]);	
        			}
        		}
        		if (killFlag == 0)
        		{
        			if (atoi(pl->stage[0].argv[1]) <= 0 || atoi(pl->stage[0].argv[1]) > jobIndex)
        				///if the supplied job number is not a valid job index
        				///then print error
        				fprintf(stderr, "%s: No such job.\n", pl->stage[0].argv[1]);
        			else
        				killProcess(atoi(pl->stage[0].argv[1])-1, jobs[atoi(pl->stage[0].argv[1])-1]->id);
        		}
        	}
        	skip = 0;
        }
        else
        {
        	///pipe/redirect as necessary
        	numExits = 0;
        	//int i;
        	//for (i = 0; i < pl->length; i++)
        	//{
        		
	        	//else
	        	//{
	        		//handle backgrounding "&"
	        			//find the &
		        		int j;
		        		int andFound = 0;
		        		int pipeFound = 0;
		        		for (j = 1; j < strlen(pl->cline); j++)
		        		{
		        			if (pl->cline[j] == '|')
		        			{
		        				//fprintf(stderr, "Pipelines cannot be backgrounded\n");
		        				pipeFound = 1;
		        			}
		        			else if (pl->cline[j] == '&')
		        			{
		        				//error if & is not the last arg, exec nothing
		        				if (pipeFound == 1)
		        				{
		        					fprintf(stderr, "Pipelines cannot be backgrounded\n");	
		        				}
		        				else if (j != strlen(pl->cline) - 1)
		        				{
		        					andFound = 1;
		        					fprintf(stderr, "Junk after '&'.\n");
		        				}
		        				else if (pl->cline[j-1] == ' ')
		        				{
		        					andFound = 1;
		        					pl->cline[j] = '\0';
		        					//backExec(pl->stage[0].argv[0], pl->stage[0].argv, pl->cline);
		        					back = 1;
		        				}
		        			}
		        		}
		        if (pl->length >= 2)
	        	{
	        		///pipe if the pipline has 2 or more stages
	        		pipeCmd(pl);
	        	}
	        	else if (pl->stage[0].outname != NULL && pl->stage[0].inname != NULL)
	        	{
	        		redirectBoth(pl->stage[0].argv, pl->stage[0].inname, pl->stage[0].outname);
	        	}
	        	else if (pl->stage[0].outname != NULL)
	        	{
	        		///otherwise redirect output if there is an outfile
	        		redirectOutput(pl->stage[0].argv, pl->stage[0].outname, pl->cline);	
	        	}
	        	else if (pl->stage[0].inname != NULL)
	        	{
	        		///otherwise redirect input if there is an infile
	        		redirectInput(pl->stage[0].argv, pl->stage[0].inname, pl->cline);	
	        	}
		        else if (andFound == 0)
		        {
			        //execute if not a built-in command
			        execute(pl->stage[0].argv[0], pl->stage[0].argv, pl->cline);
			}
			back = 0;
	        	//}
	        	
	        //}
        }
      }
      free_pipeline(pl);   
      fflush(stdout);       /* also frees line */

      lineno++;  /* readLongString trims newlines, so increment it manually */
    }
    if (run )
    {     
    	if (script == 0)            /* assuming we still want to run */
      		prompt(promptstr);
    }
  }
  return 0;
}
Ejemplo n.º 10
0
int main(int argc, char * argv[])
{
	//variables
	static unsigned long commHistSize = 10;
	static const char USAGE_MESS[] = "Usage: mysh [-v] [-h pos_num]";

	if(argc > 1) //parse options if any given
	{
		if(strcmp("-v", argv[1]) == 0) //if verbose option given
			verboseMode = 1;
		else if(strcmp("-h", argv[1]) == 0) //if history option given
		{
			if(argc > 2) //convert to long and update if number given
			{
				long temp = strtol(argv[2], NULL, 10);
				if(temp > 0) //if positive num, update command history
					commHistSize = temp;
				else
				{
					fprintf(stderr, "%s\n", USAGE_MESS);
					return EXIT_INVALID_ARG;
				}
			}
			else //no number given
			{
				fprintf(stderr, "%s\n", USAGE_MESS);
				return EXIT_INVALID_ARG;
			}
		}
		else //if unrecognized argument
		{
			fprintf(stderr, "%s\n", USAGE_MESS);
			return EXIT_INVALID_ARG;
		}
	}

	//initialize all necessary variables
	static unsigned long curCommand = 1; //current command index
	char *prevCommands[commHistSize]; //command history array
	initHistory(prevCommands, commHistSize); //initialize prevCommands array

	//variables needed for getting input
	char *inputBuf = NULL;
	size_t lineLen = 0;
	int progRet = EXIT_SUCCESS;
	int ret = -1;

	printf("mysh[%lu]> ", curCommand); //print prompt
	//get line, process while we have actually read bytes
	while((ret = getline(&inputBuf, &lineLen, stdin)) > 0)
	{
		if(ret == 1) //if only a new line given, prompt and start again
		{
			printf("mysh[%lu]> ", curCommand);
			continue;
		}

		//handle if ! was given, get given command history index
		if(inputBuf[0] == '!')
		{
			//get the num after the !
			unsigned long tempNum = 0;
			ret = sscanf(inputBuf, "!%lu", &tempNum);
			char *tempBuf = NULL;

			if(ret > 0) //if no number found there was an error. keep it NULL
				tempBuf = getCommand(prevCommands, commHistSize, curCommand,
									 tempNum);

			if(!tempBuf) //if null, there was an error
			{
				fprintf(stderr, "Invalid command index number given.\n");
				printf("mysh[%lu]> ", curCommand);
				continue;
			}
			else //if not null, realloc and copy string to inputBuf
			{
				char *temp = (char*)realloc(inputBuf, strlen(tempBuf) + 1);
				if(temp)
				{
					inputBuf = temp;
					strcpy(inputBuf, tempBuf);
				}
			}
		}
		else //remove trailing newline if no ! given
			inputBuf[ret - 1] = '\0';

		if(verboseMode)
			printf("\tCommand: %s\n\n", inputBuf);

		if(!strncmp(inputBuf, "quit", 4))
			break;

		//add command to command history
		ret = addCommand(prevCommands, commHistSize, inputBuf, curCommand);
		if(ret) //if nonzero, something failed
		{
			perror("mysh");
			ret = 1;
			progRet = EXIT_FAILURE;
			break;
		}

		//tokenize input and get it in args
		char **args = NULL;
		int argSize = split(inputBuf, &args);

		//we don't need inputBuf any more so free it
		free(inputBuf);
		inputBuf = NULL;

		if(argSize < 0) //if error found parsing args.
		{
			perror("mysh");
			ret = 1;
			progRet = EXIT_FAILURE;
			break;
		}

		//process commands and do what they ask
		if(!strcmp(args[0], "history")) //if they gave history command
			printHistory(prevCommands, commHistSize, curCommand);
		else if(!strcmp(args[0], "verbose")) //turn verbose on/off
		{
			if(argSize > 2)
				verbose(args[1]);
			else
				verbose("");
		}
		else if(!strcmp(args[0], "help")) //print help for mysh
			help(USAGE_MESS);
		else if(!strcmp(args[0], "echo")) //echo their given args
			echo(args, argSize - 1, 1);
		else //external command, fork dat
		{
			int runRet = 0;
			//fork/exec command, if -2, child failed so end gracefully
			if((runRet = run(args)) == -2)
			{
				destroyArgs(args, argSize);
				ret = 1;
				progRet = runRet;
				break;
			}
			if(runRet || verboseMode)
				printf("Command status: %d\n", runRet);
		}

		//free some memory and print prompt before starting again
		destroyArgs(args, argSize);
		printf("mysh[%lu]> ", ++curCommand);
	}

	//memory management
	destroyHistory(prevCommands, commHistSize);
	free(inputBuf);

	//if CTRL-D pressed/EOF, print newline for formatting
	if(ret < 1)
		putchar('\n');

	return progRet;
}
Ejemplo n.º 11
0
int main(void)
{
	int should_run = 1;
	int argsIndex = 0;
	numCommands = 0;

	char *args[MAX_LINE/2 + 1];
	char line[MAX_LINE];
	char lineCopy[MAX_LINE];
	char *lastChar;

	while (should_run) {
		*lastChar = ' ';
		argsIndex = 0;
		fflush(stdout);
		printf("osh>");
		fflush(stdout);
		//string reading code
		gets(line);

		//get params from line
		parseLine(line,lineCopy,args,lastChar);

		//command execution code
		if(args[0]) {
			//repeat last command
			if(strcmp("!!",args[0]) == 0) {

				if(numCommands == 0) {
					printf("No commands in history \n");
					fflush(stdout);
				}else {
					strcpy(line,history[9]);
					parseLine(line,lineCopy,args,lastChar);
					fflush(stdout);
					executeCommand(args[0],args,*lastChar);
					fflush(stdout);
					addToHistory(lineCopy);
				}
			//execute given command
			} else if(args[0][1] && args[0][0] == '!') {
				args[0]++;
				int command = atoi(args[0]);
 				int commandIndex =  command - numCommands + 9;
 				if(commandIndex > 9 || commandIndex < 0){
 					printf("No such command in history \n");
 					fflush(stdout);
 				}else{
	 				strcpy(line,history[commandIndex]);
					parseLine(line,lineCopy,args,lastChar);
					fflush(stdout);
					executeCommand(args[0],args,*lastChar);
					fflush(stdout);
					addToHistory(lineCopy);
				}
			//exit command
			} else if(strcmp("exit",args[0]) == 0){
				should_run = 0;
			//print history command
			} else if(strcmp("history",args[0]) == 0) {
				fflush(stdout);
				printHistory();
				fflush(stdout);
			//exec command
			} else {
				fflush(stdout);
				executeCommand(args[0],args,*lastChar);
				fflush(stdout);
				addToHistory(lineCopy);
			}
		}
	}
}
Ejemplo n.º 12
0
int main(int argc, char *argv[]) 
{
	
		char *line;
		char *prompt = "myshell>";
		char *envPrompt = "DASH_PROMPT";
		char *args[2048];
		char *str;
		char *multiCmd[2048];
				
		int i=0;
		int flag;
	        int jobid;
		int code;
		int fd1,fd2;	
					
		tcpid = getpgrp();
		
		ObjectPtr myObj;
		NodePtr node;

		lst = createList(getKey,toString,freeObject);  // Creating a List
			
		prompt = getenv(envPrompt);

		if(prompt == NULL)
			prompt = "myshell>";
		
		using_history();

		if(signal(SIGINT,signalHandling) == SIG_ERR){}
		
		if(signal(SIGTSTP,signalHandling) == SIG_ERR){}

		if(signal(SIGTTOU,SIG_IGN)==SIG_ERR){}
		if(signal(SIGCHLD,SIG_DFL)==SIG_ERR){}

		if((argc == 2) && (strcmp(argv[1],"-v")==0))
		{
			printf("%s\n",svn_version());
			exit(0);
		}
			
		code = sigsetjmp(env,TRUE);
				
		while ((line=readline(prompt))) 		// Reading Input
		{
			if(line==NULL)
			{	
				printf("\n read line failed \n");
				continue;
			}
			
		      	add_history(line);
 
			str = (char *)mymalloc(sizeof(char)*(strlen(line)+1));
			strcpy(str,line);
											
			if(str[0] == '&' || str[0] == ';')
			{
				printf("dash: syntax error near unexpected token %c \n",str[0]);
				freeVar(line,str,args);
				continue;
			}
			
			while((pid = waitpid(-1,NULL,WNOHANG)) > 0)
			{
				node = search(lst,pid);
				((ObjectPtr)(node->obj))->jobStatus = 0;
				printf("%s\n",(*toString)(node->obj));
				removeNode(lst,node);
			}
			
						
			if(checkMultiCmd(str, multiCmd)== -1)
				continue;
			
			while(multiCmd[i])			
			{
				flag = searchAmp(multiCmd[i]);	// Function to check if there is an '&' in the Command
				struct IORedirect *ior = tokenize(multiCmd[i],args);
				if((int)ior == -1)
				break;		       // Parsing the Command that needs to be executed
				
				if(exitLogout(multiCmd[i]))	// Function to check Exit and Logout Commands
				{
					if(checkStoppedJobs())
					{
						//memset(multiCmd,0,sizeof(multiCmd));
						break;
					}
					else
					{
						freeVar(line,str,args);
						freeList(lst);
						memset(multiCmd,'\0',sizeof(multiCmd));
						myfree(ior);
						exit(0);
					}
				}
				if(checkEOF(multiCmd[i]))			// Function to check EOF
				{
					freeVar(line,str,args);
					memset(multiCmd,'\0',sizeof(multiCmd));	
					freeList(lst);
					myfree(ior);
					exit(0);
				}
				if(checkEmptyCmd(multiCmd[i]))		// Function to Check if Enter Key is pressed
				break;
			
			
				if((strcmp(args[0],"cd")==0) && (flag == FALSE))  // Function to check if 'cd' command is used
				{
					chgDir(args);
					break;
				}
			
				if((strcmp(args[0],"jobs")==0) && (flag == FALSE)) // Function to check if 'jobs' command is used
				{
					jobsCmd();
					break;
				}
			
				if(strcmp(args[0],"history")==0)
        		        {
                     	        	printHistory(args, str, flag);
	                                break;
       			        }
	
				if((strcmp(args[0],"bg") == 0) && (flag == FALSE))
				{
					bgCmd(args);
					break;
				}
					
				if((strcmp(args[0],"fg")==0) && (flag == FALSE))
				{
					fgCmd(args);
					break;
				}
			
				if(ampCount(multiCmd[i]))
				{
					printf(" dash: syntax error near unexpected token '&' \n");
					break;
				}
				if ( (pid = fork()) < 0)		// Forking a Process
				err_sys("fork error");
					
				else if (pid == 0) 
				{		
					struct stat buf;
					/* child */
    				     	if(flag == TRUE)
					{
						if(setpgid(0,0)!=0)
						perror("setpid() error");
					
						if(tcsetpgrp(0,tcpid)!=0)
						perror("tcsetpgrp() error");
					}
				
					if(ior->input != NULL)
					{
					
						if((fd1 = stat(ior->input,&buf))==-1){
                	                        printf("dash: %s file does not exist\n",ior->input);
                       			        break;
                                        	}

                                        	if((fd1= access(ior->input,R_OK))==-1){
                                   	        printf("dash: %s permission denied\n",ior->input);
                                        	break;
                                        	}
		                                if((fd1 = open(ior->input,O_RDONLY))==-1){
                		                printf("dash: %s inpRedirect opening failed\n",ior->input);
                                	        break;
                               		        }
                                      		else {
							close(0);
					 		dup(fd1);
						}
					}
	
					if(ior->output != NULL)				
					{
						/*if((fd1= access(ior->output,W_OK))==-1){
                        	                printf("dash: %s permission denied",ior->output);
                                	        break;}*/
                                        	if((fd2=open(ior->output,O_WRONLY|O_TRUNC|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH ))==-1){
                                        	printf("dash: %s outRedirect opening failed\n",ior->output);
                                       		break;}
                                       		else{
							close(1);
							dup(fd2);
						}
					}
					if (setpgid(0,0) != 0)
       		         		perror("setpgid() error");

			                if (tcsetpgrp(0, getpid()) != 0)
                			perror("tcsetpgrp() error");
					
					execvp(args[0],args);
					err_ret("couldn't execute: %s", line);
					exit(127);
				}
				if(flag == TRUE && (*args[0] !='\0'))
				{
					jobid = assignJobId();
					myObj = createObject(pid,multiCmd[i],jobid,1); 
					node = createNode(myObj);
					addAtRear(lst,node);
				
					printf("[%d] %d %s &\n",((ObjectPtr)(node->obj))->jobId, ((ObjectPtr)(node->obj))->key, ((ObjectPtr)(node->obj))->data);
					
					if ( (pid = waitpid(pid, &status, WNOHANG)) < 0)
					err_sys("waitpid error");
					if((tcsetpgrp(0,tcpid))!=0)
					perror("tcsetgroup error");
				
				}
				else
				{
				
					if ( (pid = waitpid(pid, &status, 0|WUNTRACED)) < 0)
					err_sys("waitpid error");
					if((tcsetpgrp(0,tcpid))!=0)
					perror("tcsetgroup error");
					if(WIFSTOPPED(status))
					{
						jobid = assignJobId();
                				myObj = createObject(pid,line,jobid,2);
                				node = createNode(myObj);
                				addAtRear(lst,node);
                				printf("%s\n",(*toString)(node->obj));
					}
			
				}
			i++;
			}
			freeVar(line,str,args);
			memset(multiCmd,'\0',sizeof(multiCmd));
			i=0;
		}
		freeList(lst);
		exit(0);
	}
Ejemplo n.º 13
0
void runInternal(int m){
int result;
char *promptBuff;
promptBuff = NULL;
	switch(m){
		case 0:
			strcpy(home, getenv("HOME"));
			int i = chdir(home);
			if(i<0) printf("Couldn't restore\n");
			else{
				printf("directory changed\n");
				printf("HOME: %s\n", home);
			}
			exit(0);
		case 1:
			/*if(par[1] != NULL){
					printf("%s is an Unknown command 2\n", *par);
			}
			else{*/
				printf("PATH = %s\n", getenv("PATH"));
				/*}*/
			break;
		case 2:
			if(par[1] == NULL){
					printf("%s is an Unknown command 3\n", *par);
			}
			else{
				int newPath = setenv(par[1], par[1], 0);
				printf("%d", newPath);
				/*const char* path = getenv("PATH");
				printf("PATH :%s\n",(path!=NULL)? path : "getenv returned NULL");*/
			}
			break;
		case 3:
			
			result= 0;
			if(par[1] == NULL){
				chdir("..");
			}
			else{
				result = chdir(par[1]);
				
				if(result == 0){
					printf("\nDirectory changed to %s\n", par[1]);
				}	
				else{
					switch(errno){
					case EACCES: perror("Permission denied");
						break;
					case EIO:	 perror("");
						break;
					case ENAMETOOLONG: perror("");
						break;
					case ENOTDIR: perror(""); 
						break;
					case ENOENT: perror(""); 
      						break;
					}
				}
				
			}
			break;
		case 4:
			printHistory();			
			break;
		case 5: if(par[1] == NULL || par[2] == NULL) {
			printAliases();
		} else {
			addAlias();
		}	
	}	
	
}
Ejemplo n.º 14
0
/**
 * ADC_sample_on_USER_with_History:
 * Samples the potentiometer when the USER input button
 * is pressed. Waits until the user input button is pressed
 * before sampling. Prints out history after sampling.
 */
void ADC_sample_on_USER_with_History(void){
	//Wait for USER press
	USER_debounce();
	addToHistory( ADC_read() );
	printHistory();
}
Ejemplo n.º 15
0
int main(void)
{
	system("clear");
	char in_buffer[MAX_LINE]; /* to store the input commands*/
	int background;             /*is set if '&' is given at end of command */
	char *args[MAX_LINE/+1];/* to have 40 arguments */
	char checkCommand[10]; /* To track the input like !! and !N*/
	pid_t pid;
	int i;
	int shouldrun = 1;
	while (shouldrun)  //while runs always, unless user enter exit
	{           
		background = 0;
		printf(" COMMAND->\n");
		setupCommand(in_buffer,args,&background);  /* To get next command */
		if(strcmp(args[0],"exit")==0)	//if user enters exit, it exits out
		{
			printf("exiting\n");
			shouldrun=0;
			exit(0);
		}
		int k,j,status_flag;
		k = 0;
		j=0;
		int histCounter =0; /* This is loop counter to traverse through history array*/
		int lengthArgs = strlen(args[0]); 
		status_flag=0; /* This is to track whether command entered will be executed or not by execvp*/
		int no_commands=0;
		int hist_flag = 0; /* This flag is to test whether !! or !N has been given as input or not*/
		int maxIndex = count;
		int minIndex =0;  
		if(count>9)
		minIndex = count - 9;
		char* histHold[20];
		strcpy(checkCommand,args[0]);
		int position_value = 0; /* This will hold what position will fetched from history */
		if(lengthArgs<=2)
			position_value = (int)checkCommand[1] - '0'; /* Convert the character digit to numeric value*/

		/**
			*This else loop will work in this way: if !10 is given then position to be fetched from is 10
			* It will extract the value given after '!' and will store in variable position_value
		*/		
		else
		{
			int power = lengthArgs -2;	
			int value = 0;
			int loop=0;
			int hold;
			/**
				* This for loop takes value N from !N
				* It then parse each digit from N and forms the numeric value
				* If input is given as !10 then it will take out 12
				* It will parse each digit (1 and 0)
				* It will form the numeric value as 1*(10 power of 1) + 2 * (10 power of 0)
			*/	
			for(loop=1;loop<lengthArgs;loop++)
			{
				hold = (int)checkCommand[loop] -'0';
				value = value + hold * pow(10,power);
				power--;
			}
			position_value = value;
		}
		/* This block will fetch the command from history only when the input pattern will be like !! or !N*/
		if(checkCommand[0] == '!' )
		{
			if((checkCommand[1] == '!' && count>0) || 
				(position_value >= minIndex 
					&& position_value <= maxIndex))
			{
				int position = 0; /* This is initialized to 0 to get the latest command from history*/
				/*Check for the pattern !N*/
				if(checkCommand[1]!='!')
				{
					position =  maxIndex - position_value;
				}
				memset(&hist_array[0], 0, sizeof(hist_array)); /* Array initialization*/
				/**
					* This while loop will take each character (except null and enter) from history array
					* It will put the character in a temporary 1D array
				*/
				while (history[position][j] != '\n' && history[position][j] != '\0')
				{
					hist_array[k] = history[position][j];
					j++;
					k++;
				}

				/**
					*This is to make an entry in the history array 
					* with the command corresponding to the position !! 
					* or !N
				*/
				for (histCounter = 9;histCounter>0; histCounter--)
					strcpy(history[histCounter], history[histCounter-1]);

				strcpy(history[0],hist_array);
				count++;
				printf("Command fetched : %s\n",hist_array);

				/** 
					* This block will get the command from the history for the given position.
					* Commands are spliited by space if it contains more than one word
					* It will store the command in a pointer of character array
					* The pointer character array is passed to execvp to execute
				*/
				int hist_array_length = strlen(hist_array); /* Get the length of the command fetched from history*/
				int arrayCounter = 0;
				char holdCharacter; /* This will hold the each character of the command while parsing the command*/
				int histHoldCounter = 0;
				int blankPossible = 0; /* This is handle multiple blanks between words in a command*/
				histHold[histHoldCounter] = (char*) calloc(1, sizeof(char)); /* Dynamic Initialization*/
				/**
					* This for loop will parse the temporary 1D array
					* characters are concatenated and put in the current index of array of character pointers
					* If the character is space then next index of pointer array is initialized
				*/
				for(arrayCounter =0 ;arrayCounter<hist_array_length;arrayCounter++)
				{
					holdCharacter = hist_array[arrayCounter];
					if(holdCharacter != ' ')
					{
						histHold[histHoldCounter] = strcat(histHold[histHoldCounter],&holdCharacter);
						blankPossible = 1;						
					}
					if(holdCharacter == ' ')
					{
						/*handle multiple blank*/
						if(blankPossible == 1 )
						{
							histHoldCounter++;
							histHold[histHoldCounter] = (char*) calloc(1, sizeof(char));
							blankPossible = 0;
						}
					}
				}
				/* Set the immediate next index as zero after populating it with the parsed command words*/
				histHold[histHoldCounter + 1 ] = NULL; 
				status_flag = 1;
				hist_flag = 1;
				/* Block ends here */ 
			}
			else 
			{
				if(count == 0)
					printf("No commands in history\n");
				else 
				{
					printf("No such command in histoy\n");
					no_commands = 1; //flag used to stop creating processes if there are no such commands to execute
				}
				status_flag = 1; //flag used to stop executing execvp if there are no commands to execute
			}
		}
		/* This block is to print the history of commands when user give input command as 'history'*/
		if(strcmp("history",args[0])==0) 
		{
			if(count>0)
			{
				printHistory();
				status_flag = 1;
			}else
			{
				printf("No commands in history\n");
				status_flag = 1;
			}

		}
		if((strcmp("history",args[0])!=0) && (no_commands == 0)) //conditions to check when to create processes
			pid = fork();
		int pid_child = 0;
		if (pid < 0)
		{
			printf("Fork failed.\n");
			exit (1);
		}

		/*the child process will invoke execvp()*/
		else if (pid == 0)
		{
			pid_child = getpid(); //getting the pid of child process
			if(hist_flag == 1)
			{
				status_flag = 1;
				execvp (histHold[0], histHold); //executing of command fetched from history
			}
			if(status_flag == 0) 
			{
				if (execvp (args[0], args) == -1) //checking whether command has executed properly or not. If it cannot execute, displaying error executing command
				{
					printf("Error executing command\n"); 
					kill(pid_child,SIGKILL);//if command gives an error, the child process has to be killed explicitly. If not, program won't exit when exit command is given.
				}
			}
		}

		/**
			*if background == 0, the parent will wait,
			* else returns to the setupCommand() function.
		*/
		else
		{
			if (background == 0)
			waitpid(pid,NULL,0);
		}
	}
}
Ejemplo n.º 16
0
void runInternal(int m){
int result;
char *promptBuff;
promptBuff = NULL;
	switch(m){
		case 0:
			strcpy(home, getenv("HOME"));
			int i = chdir(home);
			if(i<0) printf("Couldn't restore\n");
			else{
				printf("directory changed\n");
				printf("HOME: %s\n", home);
			}
			exit(0);
		case 1:
			/*if(par[1] != NULL){
					printf("%s is an Unknown command 2\n", *par);
			}
			else{*/
				printf("PATH = %s\n", getenv("PATH"));
				/*}*/
			break;
		case 2:
			if(par[1] == NULL){
					printf("%s is an Unknown command 3\n", *par);
			}
			else{
				int newPath = setenv(par[1], par[1], 0);
				printf("%d", newPath);
				/*const char* path = getenv("PATH");
				printf("PATH :%s\n",(path!=NULL)? path : "getenv returned NULL");*/
			}
			break;
		case 3:
			
			result= 0;
			if(par[1] == NULL){
				chdir(home);
			}
			else{
				result = chdir(par[1]);
				if (getcwd(promptBuff, sizeof(par[1])) == NULL);
				else{
					printf("FAILED\n");
				}
				if(result == 0){
					printf("\nDirectory changed to %s\n", par[1]);
				}	
				else{
					switch(result){
					case EACCES: perror("Permission denied");
						break;
					case EIO:	 perror("An input output error occured");
						break;
					case ENAMETOOLONG: perror("Path is too long");
						break;
					case ENOTDIR: perror("A component of path not a directory"); 
						break;
					case ENOENT: perror("No such file or directory"); printf("enoent\n");
      
					default: printf("Couldn't change directory to %s", par[1] ); 
					}
				}
				
			}
			break;
		case 4:
			printHistory();
			
		}	
		
	
}
Ejemplo n.º 17
0
/** parse: parse user input and call the appropriate commands
 * @param input - user input (beginning with "cd ")
 * @return ERROR_CODE if anything throws an error
 */
int parse(char * input) {

	// helpers
	char util[SIZE];
	int savedSTDOUT = -1;

	// grab command
	strcpy(util, input);
	char * ptr = strtok(util, "> ");
	char * cmd = ptr;

	/* builtin: '!!' and '!n' */

	// '!!' run last command
	if (strcmp(bangbang, cmd) == 0) {

		// no commands yet
		if (historyCount == 0) {
			return throwError();
		}
		strcpy(input, historyArr[historyCount-1]);

		// reset command
		strcpy(util, input);
		ptr = strtok(util, "> ");
		cmd = ptr;
	}

	// '!n' run nth command in history
	else if (strncmp(bang, cmd, 1) == 0) {
		// no commands yet
		if (historyCount == 0) {
			return throwError();
		}

		int len = strlen(cmd);

		// if we get more than just '!'
		if (len != 1) {
			int ind = 1;
			long n = atoi(&cmd[ind]); // # of the entry requested

			// if the entry # is valid and within the last 10
			if (n < historyCount && n > historyCount-10) {
				strcpy(input, historyArr[n]);

				// reset command
				strcpy(util, input);
				ptr = strtok(util, "> ");
				cmd = ptr;
			}

			// the entry # is not valid
			else { return throwError(); }
		}
		// we only got a '!'
		else { return throwError(); }
	}

	// add last command to history
	addToHistory(input);


	/* checking for redirection */

	int arrCount = countChar(input, '>');

	// if there's a redirection
	if (arrCount > 0) {
		char * out = NULL;
		int args = 0;

		// while there are args
		while (ptr != NULL) {
			// more than one '>'
			if (arrCount > 1) { return throwError(); }
			// first argument
			else if (args == 0) {}
			// second argument
			else if (args == 1) { out = ptr; }
			// more than two args
			else { return throwError(); }

			// increment
			ptr = strtok(NULL, "> ");
			args++;
		}

		// check that we have 2 args and that the '>' comes after the two args
		if (args != 2 || strlen(out) + strlen(cmd) < findFirst(input, '>')) {
			return throwError();
		}

		// set redirect for outfile
		int outfile = open(out, O_RDWR|O_TRUNC|O_CREAT, S_IRUSR|S_IWUSR|S_IXUSR);
		savedSTDOUT = dup(STDOUT_FILENO);
		dup2(outfile, STDOUT_FILENO);
		close(outfile);
	}

	// recopy util
	strcpy(util, input);
	cmd = strtok(util, "> ");


	/* remaining builtins */

	// cd
	if (strcmp(cd, cmd) == 0) {
		changeDirectory(input);
	}

	// print working directory pwd
	else if (strcmp(pwd, cmd) == 0) {
		memset(&util[0], 0, sizeof(util));
		getcwd(util, SIZE);
		strcat(util, "\n");
		write(STDOUT_FILENO, (void*) util, sizeof(util));
	}

	// history
	else if (strcmp(history, cmd) == 0) {
		printHistory();
	}

	// wait
	else if (strcmp(_wait, cmd) == 0) {
		wait(0);
	}

	// exit
	else if (strcmp(ciao, cmd) == 0) {
		clearStack();
		clearCopyStack();
		return FORCE_EXIT;
	}

	// reset bools
	if (savedSTDOUT != -1) {
		dup2(savedSTDOUT, STDOUT_FILENO);
		savedSTDOUT = -1;
	}
	return SUCCESS;
}
Ejemplo n.º 18
0
/**
* Hauptmethode
*/
int main(int argc, char *argv[]) {
	hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
	char o;
	char boardMode = 0; // 0/1
	char fullScreen = 1;
	char from[] = "??";
	char to[] = "??";
	char filename[255];
	char moves[28 * 16 * 2]; // keine Initialiserung!
	short movesCounter = 0;
	short board[120];
	int eval;
	int okay;
	int i;

	struct GameState gameState;
	struct GameState gameStateCopy;
	createStartBoard(board);
	setGameState(&gameState, board, 0, 3, 4);

	srand((unsigned int) time(NULL));  // Zufallsgenerator initialisieren

	if (fullScreen) system("cls");

	do {
		printf("\nSpieler: %i, Halbzug: %i\n", gameState.turnNumber % 2, gameState.turnNumber);
		printBoard(gameState.board, 0, boardMode);

		COLOR(128);
		printf("\n> Kommando:");
		COLOR(COLOR_DEFAULT);
		printf(" ");
        scanf("%c", &o); // Auf Char scannen
        fflush(stdin);

        if (fullScreen && o != 'm') system("cls");

        switch (o) {
        	case 'x':
        		// "magic" move - alles ist moeglich. Auch, Fehler zu produzieren.
        	case 'm':
        		printf("Zug von: ");
        		scanf("%s", from);
        		fflush(stdin);

        		printf("Zug nach: ");
        		scanf("%s", to);
        		fflush(stdin);

        		if (strlen(from) != 2 || strlen(to) != 2) {
        			printError("Ungueltige Koordinaten!\n");
        		} else {
        			autoSave(&gameState);
        			if (o == 'x') {
						doMovePartial(&gameState, convertCoordToIndex(from), convertCoordToIndex(to));
						doMoveFinal(&gameState, convertCoordToIndex(from), convertCoordToIndex(to));
        			} else {
        				if (doUserMove(&gameState, convertCoordToIndex(from), convertCoordToIndex(to))) system("cls");
        			}
        		}
        		break;
        	case 'n':
        		gameState.turnNumber--;
				printInfo("Zug zurueck.\n");
        		break;
        	case 'a':
        		do {
        			autoSave(&gameState);
        			okay = aiMove(&gameState, 0);
        		} while (autoMode && okay && ((gameState.turnNumber % 2 == 0 && gameState.ai0) || (gameState.turnNumber % 2 == 1 && gameState.ai1)));
        		break;
        	case 'c':
        		printInfo("Schach: %i\n", isCheck(&gameState));
        		break;
        	case 'h':
        		printHistory();
        		break;
        	case 'g':
        		generateMoves(&gameState, moves, &movesCounter);
        		printInfo("%i moegliche Zuege (ohne Beruecksichtigung von Schach).\n", movesCounter / 2);
				for (i = 0; i < movesCounter; i += 2) {
					printf("Zug mit %i von %i nach %i.\n", gameState.board[moves[i]], moves[i], moves[i + 1]);
				}
        		break;
        	case 'v':
        		eval = evaluateBoard(gameState.board);
        		printInfo("Evaluation (aus Sicht von weiss): %i\n", eval);
        		break;
        	case 't':
        		copyGameState(&gameState, &gameStateCopy);
    			okay = aiMove(&gameStateCopy, 3);
        		break;
        	case 'o':
        		okay = loadOpeningBookMove(&gameState, from, to);
        		if (okay) {
        			printInfo("Zugvorschlag aus dem Eroeffnungsbuch: mit %c von %s nach %s", getPieceSymbolAsChar(gameState.board[convertCoordToIndex(from)]), from, to);
        		} else {
        			printInfo("Das Eroeffnungsbuch enthaelt keinen passenden Zug!");
        		}
        		break;
        	case 's':
        		saveGame(&gameState, "quicksave", 1);
        		break;
        	case 'r':
				loadGame(&gameState, "quicksave");
        		break;
        	case 'l':
        		system("dir savegames\\*.sav /B");
				printf("\nLade Datei (Endung nicht angeben):\n");
				scanf("%s", filename);
				fflush(stdin);

				loadGame(&gameState, filename);
        		break;
        	case 'u':
        		loadAutoSave(&gameState);
        		break;
        	case 'b':
        		boardMode = (1 - boardMode);
        		printInfo("Brettdarstellung gewechselt auf: %i\n", boardMode);
        		break;
        	case 'd':
        		debugMode = (1 - debugMode);
        		printInfo("Debugmodus gewechselt auf: %i\n", debugMode);
        		break;
        	case '?':
        		printf("m (move)\tEinen Zug durchfuehren.\n");
        		printf("n (next)\tDen Spieler wechseln (ohne Zug, regelwidrig!)\n");
        		printf("a (ai)\t\tKI einen Zug durchfuehren lassen.\n");
        		printf("h (history)\tDen Spielverlauf anzeigen.\n");
        		printf("c (check)\tStellung auf Schach pruefen.\n");
        		printf("g (generate)\tMoegliche Zuege anzeigen lassen.\n");
        		printf("v (value)\tBewertung der Stellung anzeigen lassen.\n");
        		printf("t (tip)\t\tDie KI einen Zug-Tip anzeigen lassen.\n");
        		printf("s (save)\tQuicksave-Spielstand anlegen.\n");
        		printf("r (reload)\tQuicksave-Spielstand laden.\n");
        		printf("l (load)\tSpielstand laden (Dateiname angeben).\n");
        		printf("u (undo)\tLetzten Zug zuruecknehmen.\n");
        		printf("b (board)\tBrettdarstellung wechseln (fuer Debuggging).\n");
        		printf("d (open)\tDebugausgaben aktivieren/deaktivieren.\n");
        		printf("? (help)\tDiese Hilfe zu den Kommandos anzeigen lassen.\n");
        		printf("e (exit)\tDas Programm beenden.\n");
        		break;
        	case 'e':
        		// do nothing
        		break;
        	case '\n':
        		// do nothing
        		break;
        	default:
        		printError("Unbekannter Operator: %c\n", o);
        		break;
        }
        fflush(stdin);
	} while (o != 'e');

	return 0;
}