0

So hey everybody, I know it's a very popular implementation so I think I don't need to explain so much. Now what I'm doing in the shell is the pipe action, and before I copy it to my big shell I want to see it works in an example of "ls -l | tail -n 2". So this is my code, in the end of my code what it does it's just nothing, it doesn't write anything and I didn't get any segmentation fault. Thank for helpers! C code:

#include <unistd.h>
#include <stdio.h>
#include <string.h>

#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>

#define OUT 1
#define IN 0

int main ()
{
    int fd,secondSon,firstSon;
    int inAndOut[2];

    char* lsArgs[2];
    lsArgs[0]= "ls";
    lsArgs[1]= "-l";

    char* tailArgs[3];
    tailArgs[0]="tail";
    tailArgs[1]="-n";
    tailArgs[2]="2";

    pipe(inAndOut);

    firstSon = fork();
    if(firstSon==0)
    {
        fd =dup2(inAndOut[OUT],STDOUT_FILENO);
        close(fd);
        execvp(lsArgs[0],lsArgs);
    }
    else
    {
        close(inAndOut[OUT]);
    }
    secondSon = fork();
    if(secondSon==0)
    {
        fd =dup2(inAndOut[IN],STDIN_FILENO);
        close(fd);
        execvp(tailArgs[0],tailArgs);

    }
    else
    {
        waitpid(-1,&firstSon,0);
        waitpid(-1,&secondSon,0);
        close(inAndOut[IN]);
    } 
    return 0;
}

1 Answer 1

1

There are several problems.

One

fd =dup2(inAndOut[OUT],STDOUT_FILENO);
close(fd);

dup2 returns the new file descriptor, it makes no sense to close it immediately. You want to close the old one. While you're at it, you want to close the other half of the pipe.

Replace both occurrences of close(fd) with

close(inAndOut[IN]);
close(inAndOut[OUT]);

Two

You need to NULL-terminate your argument lists. Add the final element:

char* lsArgs[3];
lsArgs[0]= "ls";
lsArgs[1]= "-l";
lsArgs[2]= NULL;

and analogously in the other argument list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.