Call to the system dup2 vs. write&read

Asked

Viewed 35 times

0

I have a doubt in understanding why in some cases there are examples of conversations in the parent process and the child process - obtained through the call to the Fork system ( ) - which use read and write functions and in other cases use dup2.I am trying to create a function that allows the child to read from the father and then capitalize on what he has read from the father and write it for the father to read. I have the following function for now

int main(int argc, char *argv[])
{
    //Declaração pid
    int pid;

    //Declaração das duas variáveis que irei servir de pipe
    int fd1[2],fd2[2];

    pipe(fd1);
    pipe(fd2);

    pid = fork();

    //Verificação de erro na criação do processo filho
    if(pid < 0)
    {
        perror("Fork:");
    }

    else
    {
        //Caso estejamos no processo filho
        if(pid == 0)
        {
            close(fd1[1]); //Quando o filho estiver a ler a mensagem do pai o lado de escrita (posição 1) é fechado
            dup2(fd1[0],0); //A executar a leitura

            close(fd2[0]); //Depois o pai irá fechar o lado de leitura (posição 0) para escrever para o pai
            dup2(fd2[1],1); //A executar a escrita


        }

        //Caso estejamos no processo pai
        else
        {
            //O pai fecha no seu código os descritores que o filho utilizei no dup2
            close(fd1[0]);
            close(fd2[1]);
        }

    }

    return 0;
} 

I do not want to solve the problem because I know that this is not the purpose of the platform, but rather someone who will explain to me whether I am doing the right thing or whether I am making a mistake.

Problem statement

inserir a descrição da imagem aqui

Thank you!

1 answer

0


pipe() seems to be being used correctly in the code.

The goal of dup2() is to duplicate the file Descriptor to a set number. In the case of code, the child-process is putting a pipe in place of file Descriptor 0 which is "stdin", and another pipe in place of "stdout". This is usually only done when the child-process will call exec() then so that the new executable "inherits" the Pipes as stdin and stdout. If the child process will continue running without calling exec(), it could use the same pipe fd’s to communicate with the parent process.

  • As I understand it in this particular case, there is no need to use dup2. Just use the write and read functions to perform the exchange of information between the parent and the child. The father writes on the pipe where the son reads and the son will write on the other pipe and the father will read.

  • So yes the answer turns out to be correct because no exec is being executed ( ).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.