System call dup2 vs. write & read

0

I'm wondering why in some cases there are examples of conversations in the parent process and the child process - obtained through the fork () system call - that use the read and write functions and in other cases use the dup2.I am trying to create a function that allows me to read the child's parent and then move to uppercase what I read from the parent and write this to the parent 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 intend to solve the problem because I know that the purpose of the platform is not this but rather someone who will explain to me if I am proceeding correctly or if I am making a mistake.

Issue statement

Thank you!

    
asked by anonymous 09.04.2018 / 15:42

1 answer

0

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

The purpose of dup2 () is to duplicate the file descriptor to a defined number. In the case of code, the child process is putting a pipe in place of the file descriptor 0 which is the stdin, and another pipe in place of the stdout. This is usually done only when the child process will call exec (), 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 fd's to communicate with the parent process.

    
09.04.2018 / 16:53