Answer the question
In order to leave comments, you need to log in
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.
#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;
}
Answer the question
In order to leave comments, you need to log in
Where can there be an error?
#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 questionAsk a Question
731 491 924 answers to any question