D
D
Dmitry Bystrov2018-12-01 12:06:30
linux
Dmitry Bystrov, 2018-12-01 12:06:30

How to output a character through a pipe?

Good afternoon!
There is a task:

To establish two-way communication between processes, you can create two channels
working in different directions.
Think of a possible dialogue between two processes and implement it
using two channels.

Found on the Internet an example of two-way communication through a two-way channel.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h> 

int main(int argc, char **argv) {

int fd[2], n;
char c;
pipe(fd); 

if (!fork()) {

    write(fd[0], "c", 1);

    sleep(1);

    if ((n = read(fd[0], &c, 1)) != 1) {
        printf("Дочерний процесс. Результат чтения: %d\n", n);
        exit(0);
    }

    printf("Дочерний процесс прочитал: %c", c);
    exit(0);
}

write(fd[1], "p", 1);
if ((n = read(fd[1], &c, 1)) != 1) {
    printf("Родительский процесс. Результат чтения: %d\n", n);
    exit(0);
}

printf("Родительский процесс прочитал: %c", c);
exit(0);

return 0;
}

But when executed, the parent process returns -1.
Where can there be an error?
And can this example be suitable as a solution to the problem?
If not, what could be the solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-12-01
@Teshuhack

Where can there be an error?

man pipe: писать можно только в fd[1], читать -- только из fd[0].
Канал однонаправленный, т.е. для двунаправленной коммуникации нужно открывать два канала.
Должно быть так:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h> 

int main(int argc, char **argv) {

        int fd0[2], fd1[2], n;
        char c;
        pipe(fd0);
        pipe(fd1);

        if (!fork()) {
                close(fd0[0]);
                close(fd1[1]);

                write(fd0[1], "c", 1);

                sleep(1);

                if ((n = read(fd1[0], &c, 1)) != 1) {
                        printf("Дочерний процесс. Результат чтения: %d\n", n);
                        exit(0);
                }

                printf("Дочерний процесс прочитал: %c\n", c);
                exit(0);
        }
        close(fd1[0]);
        close(fd0[1]);
                                                                                                                                                                                                                                                                          
        write(fd1[1], "p", 1);
        if ((n = read(fd0[0], &c, 1)) != 1) {
                printf("Родительский процесс. Результат чтения: %d\n", n);
                exit(0);
        }

        printf("Родительский процесс прочитал: %c\n", c);
        exit(0);

        return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question