Created
April 18, 2017 15:04
-
-
Save mikigom/2d23b5571bc1eaa3926865dc8c32ada9 to your computer and use it in GitHub Desktop.
This file contains 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
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <unistd.h> | |
#include <wait.h> | |
#define CHUNK 1 | |
char** res = NULL; | |
char* _getln(); | |
char** _strtok_by_space(char* str, int* len); | |
void exit_handler(void); | |
int main(int argv, char* argc[]){ | |
if(atexit(exit_handler)) | |
printf("Failed to register exit_handler\n"); | |
/* Example of _getln() and _strtok() | |
*/ | |
int len, i; | |
char* a = _getln(); | |
char** res = _strtok_by_space(a, &len); | |
for(i = 0; i < (len+1); ++i) | |
printf("res[%d] = %s\n", i, res[i]); | |
/* execvp TEST | |
*/ | |
char *name[] = { | |
"/bin/bash", | |
"-c", | |
"echo 'Hello World'", | |
NULL | |
}; | |
execvp(name[0], name); | |
free(a); | |
//free(*res); | |
//free(res); | |
return 0; | |
} | |
// _getln() : Read string input with memory-efficient dynamic allocation | |
// IN : | |
// OUT : | |
// RETURN : dynamic allocated string input | |
char* _getln(){ | |
char *line = NULL, *tmp = NULL; | |
size_t size = 0, index = 0; | |
int ch = EOF; | |
while (ch) { | |
ch = getc(stdin); | |
/* Check if we need to stop. */ | |
if (ch == EOF || ch == '\n') | |
ch = 0; | |
/* Check if we need to expand. */ | |
if (size <= index) { | |
size += CHUNK; | |
tmp = realloc(line, size); | |
if (!tmp) { | |
free(line); | |
line = NULL; | |
break; | |
} | |
line = tmp; | |
} | |
/* Actually store the thing. */ | |
line[index++] = ch; | |
} | |
return line; | |
} | |
// _strtok_by_space : Return arr of string splited by space with dynamic allocation | |
// IN : str(char*) | |
// OUT : len(int*) - length of arr of string | |
// RETURN : dynamic allocated arr of string | |
char** _strtok_by_space(char* str, int* len){ | |
char* p = strtok(str, " "); | |
int n_spaces = 0, i; | |
char** res = NULL; | |
/* split string and append tokens to 'res' */ | |
while (p) { | |
res = realloc(res, sizeof (char*) * ++n_spaces); | |
if (res == NULL) | |
exit(-1); /* memory allocation failed */ | |
res[n_spaces-1] = p; | |
p = strtok(NULL, " "); | |
} | |
/* realloc one extra element for the last NULL */ | |
res = realloc(res, sizeof (char*) * (n_spaces+1)); | |
res[n_spaces] = 0; | |
*len = n_spaces; | |
return res; | |
} | |
void exit_handler(void){ | |
printf("Bye :)\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment