Last active
December 15, 2015 15:29
-
-
Save austa/5281909 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* File: main.c | |
* Author: austa | |
* | |
* Created on 27 Mart 2013 Pazar, 22:03 | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include<sys/types.h> | |
#include<unistd.h> | |
#include<string.h> | |
#include<readline/readline.h> | |
#include<readline/history.h> | |
/* | |
* | |
*/ | |
void bellek_bosalt(); | |
int calistir(); | |
int ayristir(char *); | |
char *str_cat(char[], char[]); | |
static char* argumanlar[100]; // Fonksiyonlarımız her çağrıldığında değerler değişmemesi için static olarak tanımlıyoruz. | |
static int uzunluk; // Aynı şekilde de burada static olarak tanımlandı.Bütün foksiyonlar kullanabilir. | |
int main(int argc, char** argv) { | |
char *komutum; | |
while(True){ | |
printf("$> "); | |
komutum = readline(); // Kullanıcıdan komutu okuduk | |
ayristir(komutum); // Ardından komutu boşluklar baz alınarak ayrıştırıp, diziye gönderiyoruz. | |
calistir(); // Ve tabiki diziden okuyup komutumuzu çalıştırıyoruz. | |
bellek_bosalt(); // En son da ise belleğimizi boşaltırız. | |
} | |
free(komutum); | |
return (EXIT_SUCCESS); | |
} | |
int ayristir(char *girilen_komut){ | |
add_history(girilen_komut); // aldığımız komutu boşluklar baz alınarak ayrıştırıp diziye atıyoruz. | |
char *str_ptr; | |
str_ptr = strtok(girilen_komut, " "); | |
for(len = 0; str_ptr != '\0' ; uzunluk++){ | |
argumanlar[uzunluk] = strdup(str_ptr); | |
str_ptr = strtok(NULL, " "); | |
} | |
argumanlar[uzunluk] = NULL; | |
return 0; | |
} | |
char *str_cat(char dizi1[], char dizi2[]){ | |
int i = 0, j = 0; | |
for(i = strlen(dizi1), j = 0; dizi2[j] != '\0'; i++, j++){ | |
dizi1[i] = dizi2[j]; | |
} | |
return dizi1; | |
} | |
int calistir(){ | |
char program_adi[100] = "/bin/"; | |
str_cat(program_adi,argumanlar[0]); // /bin/ + program_ismi, str_cat altta tanımlanmış bir fonksiyondur ve ikinci argümanı ilk argümanın sonuna ekler | |
int status; | |
pid_t pid; | |
pid = fork(); | |
if (!pid) { | |
int ret; | |
ret = execv(program_adi, argumanlar); | |
if (ret == -1) { | |
perror("execv"); | |
exit(EXIT_FAILURE); | |
} | |
} else if (pid == -1) | |
perror("fork"); | |
if (waitpid(-1, &status, 0) == -1) { | |
perror("waitpid"); | |
exit(EXIT_FAILURE); | |
} | |
return 0; | |
} | |
void bellek_bosalt() | |
{ | |
int i; | |
for (i = 0; i < uzunluk; i++) { | |
free(argumanlar[i]); // argumanlar[0] program adını temsil eder, ondan sonrakiler ise komutlarımızı,ve biz belleği boşaltmaya ihtiyaç duyuyoruz. | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment