static void test_redirect() 
{ 
    check_redirect(STDOUT_FILENO, STDERR_FILENO, "message"); 
    check_redirect(STDERR_FILENO, STDOUT_FILENO, "message"); 
    check_redirect(4, 5, "message"); 
    check_redirect(10, 20, "message"); 
} 
Example #2
0
int main(int argc, char *argv[]) {
	
	//Checks that only ./whoosh is entered to invoke shell
	if(argc != 1) {
		error_msg();
		exit(1);
	}
	
	int CHAR_LIMIT = 129;
	int BUFFER_LIMIT = 1024;
	char buffer[BUFFER_LIMIT];
	
	int path_num = 1;
	char* s_path[BUFFER_LIMIT];
	s_path[0] = "/bin";
	
	while(1) {
		printf("whoosh> ");
		fflush(stdout);		
		fgets(buffer, sizeof(buffer), stdin);
		
		get_line(buffer);
		
		int line_size = strlen(buffer);
		
		if(line_size > CHAR_LIMIT) {
			error_msg();
			continue;
		}
		
		//Get num of args in command 
		int num_args = count_args(buffer);
		
		if(num_args != 0) {
			
			char* myargv[num_args + 1];
			int r_count = 0;
			int last_r = 0;
			char* r_path = NULL;
			int i;
			char buf[PATH_MAX + 1];
			char *cwd;
			char *r_output;
			
			//Put each argument in myargv array
			get_args(buffer, myargv, num_args);
			
			//Check for redirect
			check_redirect(myargv, num_args, &r_count, &last_r);
		
			//Redirect error handling
			if(r_count > 1) {
				error_msg();
				continue;
			}
			else if (r_count == 1) {
				if(last_r != num_args - 2) {
					error_msg();
					continue;
				}
				if(myargv[num_args - 1][0] == '/') {
					if(chdir(myargv[num_args - 1]) == 0) {
						r_path = strdup(myargv[num_args - 1]);
					}
					else {
						error_msg();
						continue;
					}
				}
				
				r_output = malloc(strlen(myargv[num_args - 1]) + strlen(".out"));
				sprintf(r_output, "%s", myargv[num_args - 1]);	
				//Take off > and path from arguments
				num_args = num_args - 2;
			}
			
			//Set last element in myargv array to NULL
			myargv[num_args] = NULL;
	
			//Check if exit was entered
			check_exit(myargv);
			
			//Check if any built-in commands were called
			if(check_built_in(myargv, num_args, s_path, &path_num) == 0) {
				continue;
			}
			else{
				int file_exist = 0;
				
				cwd = getcwd(buf, PATH_MAX + 1);
				for(i=0; i<path_num; i++) {
					chdir(s_path[i]);
					struct stat path_buff;
					if(stat(myargv[0], &path_buff) == 0) {
						file_exist = 1;
						char *exec_path = malloc(strlen(s_path[i]) + strlen("/") + strlen(myargv[0]) + 1);
						sprintf(exec_path, "%s/%s", s_path[i], myargv[i]);
						myargv[0] = exec_path;
						chdir(cwd);
						break;
					}
				}	
				if(file_exist == 0) {
					error_msg();
					continue;
				}
				else {
					exec_cmd(myargv, r_output, r_path, r_count);
				}
			}
		}	
	}
}