Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int main(int argc, char *argv[]) {
- if(argc <= 2){
- print_env_usage();
- return 0;
- }
- char * bin = malloc(10000);
- strcpy(bin, "/bin/");
- int length = 1000;
- int start = 1;
- if(strcmp(argv[1], "-n") == 0) {
- //provided the N information
- length = atoi(argv[2]);
- if(length == 0)
- length = 1;
- start = 3;
- }
- if((strcmp(argv[2], "--") == 0 && length == 1000))
- length = 1;
- static int dashlocation;
- int i = 0;
- while(argv[i] != NULL) {
- if(strcmp(argv[i], "--") == 0) {
- i++;
- strcat(bin, argv[i]);
- dashlocation = i-1;
- break;
- }
- i++;
- }
- //CASE: there are no environment variables
- if(dashlocation == 1) {
- pid_t child = fork();
- if(child == -1) {
- free(bin);
- print_fork_failed();
- }
- else if (child == 0) {
- execv(bin, (argv+2));
- free(bin);
- print_exec_failed();
- }
- else {
- int status;
- waitpid(child, &status, 0);
- if(WIFEXITED(status) && WEXITSTATUS(status) != 1) {
- free(bin);
- return 0;
- }
- }
- }
- //CASE: there are environment variables
- char * token;
- int indexofkeys = 0;
- int return_code;
- char * important = NULL;
- char *nameofenvs [100];
- for(; indexofkeys < length; indexofkeys++) {
- int beginning = start;
- for(; beginning < dashlocation; beginning++) {
- if(indexofkeys == 0){
- token = strtok_r(argv[beginning], "=", &argv[beginning]);
- nameofenvs[beginning] = token;
- }
- if(token == NULL) {
- free(bin);
- print_env_usage();
- }
- int counter = 0;
- char crucial = *(argv[beginning]);
- while(counter < 1) {
- if (crucial == '%'){
- //percentage sign
- //printf("%s\n", argv[beginning]);
- if (important == NULL)
- important = argv[beginning];
- //printf("%s\n", "in percentage sign");
- char * percent = malloc(10000000);
- strcpy(percent, argv[beginning]);
- percent++;
- //printf("%s\n", percent);
- return_code = setenv(token, getenv(percent), 1);
- //printf("%d\n", return_code);
- if (return_code == -1){
- free(bin);
- print_environment_change_failed();
- }
- }
- else{
- char * value = strtok_r(argv[beginning], ",", &argv[beginning]);
- //no percent sign
- return_code = setenv(nameofenvs[beginning], value, 1);
- }
- counter++;
- }
- }
- pid_t child = fork();
- if(child == -1) {
- //fork did not happen
- free(bin);
- print_fork_failed();
- }
- else if (child == 0) {
- //child is executing
- execv(bin, (argv+dashlocation+1));
- free(bin);
- print_exec_failed();
- }
- else{
- //parent process
- int status;
- waitpid(child, &status, 0);
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement