Pipes, dup2 and exec ()

I need to write a shell that can trigger channels. For example, commands such as ls -l | wc -l". I successfully analyzed the command given by the user, as shown below:

"ls" = firstcmd

"- l" = frsarg

"wc" = scmd

"- l" = secarg

Now I need to use two forks, since the teams are two and the channel. The code block that I wrote to execute the command is as follows:

pid_t pid;
int fd[2];

pipe(fd);
pid = fork();

if(pid==0)
{        
    dup2(fd[WRITE_END], STDOUT_FILENO);
    close(fd[READ_END]);
    execlp(firstcmd, firstcmd, frsarg, (char*) NULL);
}
else
{ 
    pid=fork();

    if(pid==0)
    {
        dup2(fd[READ_END], STDIN_FILENO);
        close(fd[WRITE_END]);
        execlp(scmd, scmd, secarg, (char*) NULL);
    }
}

Therefore, when I run my shell and I enter the command ls -l | wc -l(for example), the result from execs does not appear, but the shell continues to work normally.

It is strange that the result of the command is displayed only when I complete my shell with "exit" or "^ C".

? ?

+4
2

, ( ). , wc - , ( ). , . waitpid , wc.

pid_t pid;
int fd[2];

pipe(fd);
pid = fork();

if(pid==0)
{
    dup2(fd[WRITE_END], STDOUT_FILENO);
    close(fd[READ_END]);
    close(fd[WRITE_END]);
    execlp(firstcmd, firstcmd, frsarg, (char*) NULL);
    fprintf(stderr, "Failed to execute '%s'\n", firstcmd);
    exit(1);
}
else
{ 
    pid=fork();

    if(pid==0)
    {
        dup2(fd[READ_END], STDIN_FILENO);
        close(fd[WRITE_END]);
        close(fd[READ_END]);
        execlp(scmd, scmd, secarg,(char*) NULL);
        fprintf(stderr, "Failed to execute '%s'\n", scmd);
        exit(1);
    }
    else
    {
        int status;
        close(fd[READ_END]);
        close(fd[WRITE_END]);
        waitpid(pid, &status, 0);
    }
}
+9

, . , fork.

:

:

#include  <fcntl.h>
#include  <stdio.h>
#include  <stdlib.h>
#include  <string.h>
#include  <sys/types.h>
#include  <sys/wait.h>
#include  <sys/stat.h>
#include  <termios.h>
#include  <unistd.h>

using namespace std;

#define INPUT_END 1
#define OUTPUT_END 0


int main(int argc, char* argv[])
{
    pid_t pid;
    int fd[2];

    pipe(fd);
    pid = fork();

    if(pid==0)
    {
        close(fd[INPUT_END]);
        dup2(fd[OUTPUT_END], STDIN_FILENO);
        close(fd[OUTPUT_END]);
        execlp("wc", "wc", "-l",(char*) NULL);
    }
    else
    { 
        pid=fork();

        if(pid==0)
        {
            close(fd[OUTPUT_END]);
            dup2(fd[INPUT_END], STDOUT_FILENO);
            close(fd[INPUT_END]);
            execlp("ls","ls","-l",(char*) NULL);
        }

        close(fd[OUTPUT_END]); close(fd[INPUT_END]);
    }  
}
+1

Source: https://habr.com/ru/post/1617162/


All Articles