Forgive me for diverting from the matter at hand in my previous answer (by suggesting the use of threads). Since I'm going in a completely new direction here, I feel compelled to add this as a separate answer.
Short version:
Please make the following changes in your program:
1. length = argc; // in place of length = sizeof(argv);
2. execl(argv[i],argv[i],0); // in place of execvp(argv[i],0);
3. #include <unistd.h> // if you haven't already
Long version:
(1) By the variable length
, I presume you want to get the total number of arguments. argv
is a pointer-to-char-pointer
, and as such is simply a memory address. If you print out the length in your program, you will notice it is always 4 (or whatever is the size of a memory address in your system).
So this:
length = sizeof(argv);
Should really be this:
length = argc;
argc
holds the total number of arguments passed when executing the process. For example,
./a.out /bin/ps /bin/ls
gives: argc = 3 (and not 2, a very common pitfall)
(2) Another issue with your program, is the execvp
call.
The prototpye for the execvp is as follows:
int execvp(const char *file, char *const argv[]);
where, argv is the list of arguments passed to the new command, very similar to the argv in your own program.
What you use in your program is:
execvp(argv[i],0);
Suppose i=1
and argv[1] = "/bin/ls"
.
What this command does is look for the /bin/ls
executable & pass a NULL pointer (0
) to it. This may lead to the following runtime error:
A NULL argv[0] was passed through an exec system call.
Referring to the exec man page,
The first argument, by convention,
should point to the filename
associated with the file being
executed.
Though it is not mandatory to pass the filename again, you certainly shouldn't pass a NULL pointer. Since you don't want to pass any arguments, I suggest you use the following execl
call, instead:
execl(argv[i],argv[i],0);
Remember that all such calls are finally converted to execve()
finally & then executed, making them equivalent eventually.
I encourage you to read more about the exec family of functions using man
.