How to run multiple command lines with exec and dup?

Viewed 23

So I am trying to run grep name /etc/passwd | cut -f2 -d: | sort > list.txt in my program by using exec, dup, fork and open. However I am not able to do the last command ´sort´, because i simply lack the understanding of what I am currently doing and what's going on. Could someone please explain to me what i am doing wrong and why? C:

The program i currently have is: ´

#include <unistd.h>

int main(void)
{
    int fda[2];
    //int fda2[2]

    pipe(fda);

    if(fork() == 0)
    {
        close(1);

        dup(fda[1]);

        close(fda[0]);
        close(fda[1]);

        execl("/bin/grep", "grep", "Alex", "/etc/passwd", 0);
        
    }
    else
    {
        close(0);

        dup(fda[0]);

        close(fda[0]);
        close(fda[1]);
        
        execl("/bin/cut", "cut", "-f2", "-d:", 0);

        //dup(fda[0]);

        //close(fda[0]);
        //close(fda[1]);

        //execl("bin/sort", "sort", "-o", "list.txt", 0);
        //close(1);

    }
    return 1;
}

´ I would appericate some help since my teammate and I both seems to be lacking some understanding in this area.

The output of the program is currently showing ´123123´, which is the password that I am trying to extract from ´passwd´. I am getting a bit confused with the ´dup´ and ´exec´ commands, how would I run another ´exec´ for the last command line ´sort´ and how to forward the password I found in passwd to a txt file?

Also the file passwd look something like this to clearify: Alex:123123

0 Answers
Related