0

I'm currently trying to build something similar to the | in linux and it should be able to take n amount of arguments as long as they are piped together. I execute these arguments (like ls, sort, etc) using execvp() by passing it the argument and then the array that holds the argument and its options.

HOWEVER, the proplem lies in that execvp() does not return anything.. so when i fork() and go into the child process, it does what it needs to do, execvp() then goes into the parent process. Now i can recursively fork again and keep on going to get as many child processes as needed and call n amounts of execvp() but I would like to know if there is ITERATIVE way of doing the same thing.

Hope I was clear enough, it's very late, so sorry for the ambiguity.

user2824512
  • 105
  • 1
  • 9

1 Answers1

0

You can use wait(&status) on each fork. Here is an example that uses argv as a list of file descriptors to open in forks and then wait for them all to finish. For exec* functions it will wait for an exit.

int main(int argc, char **argv){
    unsigned int i,fd,*status;
    for(i=1;i<argc;++i){
        if(fork()==0){
            fd = open(argv[i], 04000);
            if (fd<2) return 2;
            //do stuff with fd
            close(fd);
            //do stuff with data
            return 0;
        }
    }
    while(i--){
        wait(&status);
        //do stuff with status
    }
    return 0;
}
technosaurus
  • 7,676
  • 1
  • 30
  • 52