Recently I had an assignment where I had to make a program that takes from command line two different commands, separated with a '+', for example:
ps -lu myUsername + ls -la
The objective of the program was to run any two orders simultaneously, with any number of parameters per order, by using fork()
and exec()
. This was my solution to this problem:
Note: the original problem was meant to be run on a machine with Solaris 5.10 and c89 or c99 standard (gcc 3.4.3)
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <strings.h>
int main (int argc, char* argv[]) {
char delimiter = '+';
char* auxp; //auxiliar pointer
int i = 1;
int position;
while(i < argc){
if (strcmp("+", argv[i]) == 0) {
argv[i] = NULL;
position = i;
}
i++;
}
if (fork() == 0) {
execvp(argv[1], &argv[1]);
exit(1);
}
if (fork() == 0) {
execvp(argv[position+1], &argv[position+1]);
exit(1);
}
wait(NULL);
wait(NULL);
exit(0);
}
This was enough for the assignment but I wanted to make it work with N arguments instead of only 2. I can't reach a systematic way to find the all the addresses. Any help is appreciated, thanks in advice.