Reputation: 9
I am trying to write a program where it execs itself N times, and each time it execs itself a value x starting from 1 is incremented. N should be the only argument of the program.
For example:
./exec_test.o 4
will print:
Exec: 1
Exec: 2
Exec: 3
Exec: 4
Execs done
I only succeeded in making my values decrease from 4 instead of increase to 4:
Here is my code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char** args){
if (argc<2){ //Argument error handling
fprintf(stderr,"Usage %s number_of_iter",args[0]);
exit(EXIT_FAILURE);
}
int x = atoi(args[1]); //x = the argument used when executing
*args[1]-=1; //decrement the argument value
if (x>0){
printf("Exec : %d \n",x); //printing current argument
execv(args[0],args); //exec itself with argument decremented
perror(args[0]);
exit(1);
}
printf("Execs done \n");
}
and executing it results in this:
Exec: 4
Exec: 3
Exec: 2
Exec: 1
Execs done
Is it possible to make x increment from 1 instead of decrease from N while using only one argument for the program?
Upvotes: 0
Views: 135
Reputation: 75062
Yes. You can hold two information (current and maximum count) in one argument.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char** args){
if (argc<2){ //Argument error handling
fprintf(stderr,"Usage %s number_of_iter",args[0]);
exit(EXIT_FAILURE);
}
int max, x = 1; // set x to 1 for the first iteration (it will fail to read x)
char next_argument[128];
char* next_args[3];
sscanf(args[1], "%d_%d", &max, &x);
if (x <= max){
printf("Exec : %d \n",x); //printing current argument
// create next argument
snprintf(next_argument, sizeof(next_argument), "%d_%d", max, x + 1);
next_args[0] = args[0];
next_args[1] = next_argument;
next_args[2] = NULL;
execv(args[0],next_args); //exec itself with argument incremented
perror(args[0]);
exit(1);
}
printf("Execs done \n");
}
Upvotes: 1