Skip to content

Instantly share code, notes, and snippets.

@HayatoDoi
Last active December 21, 2016 01:46
Show Gist options
  • Save HayatoDoi/c9ad50bfbf82f5b5b61a688b38be5b38 to your computer and use it in GitHub Desktop.
Save HayatoDoi/c9ad50bfbf82f5b5b61a688b38be5b38 to your computer and use it in GitHub Desktop.
/* file name : originalShell.c
* Author : 1517914 2EP2-31 Hayati Doi
* Outline : Operating System 1 , 2nd Report
* Copyright (c) 2016, Hayato Doi
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>
#include <time.h>
#include <sys/stat.h>
#define MAXDIRBUF 1024
int getarg(char *argv[], char *buf){
int i;
bool flag = false;
for(i = 0; *buf != '\0';i++){
while(*buf == ' ' || flag){
*buf = '\0';
buf++;
}
if(*buf == '\0'){
break;
}
argv[i] = buf;
while((*buf != '\0' && *buf != ' ') || flag){
if(*buf == '\"' ){
*buf = '\0';
buf++;
if(!flag){
argv[i] = buf;
}
flag = !flag;
}
buf++;
}
}
argv[i] = NULL;
return i;
}
int main(int argc, char *argv[]){
char dir[1024];
char command[512];
char line[512];
char *largv[256];
int largc;
do{
//output directory
sprintf(line, "[%s]%% " ,getcwd(dir,MAXDIRBUF));
fprintf(stdout, "%s", line);
//read command
fgets(command, 511, stdin);
// skip to scan line.
if( sscanf(command, "%[^\n]", command ) <= 0 ){
continue;
}
largc = getarg(largv,command);
// Built-in command
if(strcmp(largv[0],"CD") == 0){
// skip to scan line.
if(largc < 2){
continue;
}
//Change directory
chdir(largv[1]);
}
else if(strcmp(largv[0],"LS") == 0){
struct dirent **namelist;
int n;
if(largc < 2){
largv[1] = ".";
}
n = scandir(largv[1], &namelist, NULL, alphasort);
while (n--) {
fprintf(stdout, "%s\n", namelist[n]->d_name);
free(namelist[n]);
}
free(namelist);
}
else if(strcmp(largv[0],"STAT") == 0){
char timestr[26];
struct stat s0;
//error
if( stat(largv[1],&s0) == -1 ){
continue;
}
ctime_r( &(s0.st_atime), timestr);
fprintf(stdout," 最終アクセス日時 : %s", timestr );
ctime_r( &(s0.st_mtime), timestr);
fprintf(stdout," 最終更新日時 : %s", timestr );
ctime_r( &(s0.st_ctime), timestr);
fprintf(stdout," 最終ファイル状態変更日時: %s", timestr );
}
// Built-out command
else{
// make child prosess
if(fork()==0){
execvp(largv[0],largv);
fprintf(stdout, "originalShell: command not found: %s\n",largv[0]);
exit(1);
}
wait(NULL);
}
}while(true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment