Я работаю над проектом, который отправляет сообщение между тремя процессами: родительский с двумя детьми. Первый процесс займет сообщение, а затем отправит сообщение второму процессу. Второй процесс будет читаться в сообщении, а затем преобразовать его перед отправкой его в третий процесс. Третий процесс будет читать в сообщении и еще больше преобразовать это сообщение. Наконец, сообщение будет отправлено обратно на первый процесс, распечатав его.Передача сообщения между тремя трубами
Это должно быть реализовано с использованием труб и системных вызовов в UNIX. Я не настолько разбираюсь в этом процессе, поэтому буду благодарен за советы и рекомендации. Ниже мой код. Спасибо!
*#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#define ERR (-1) /* indicates an error condition */
#define READ 0 /* read end of a pipe */
#define WRITE 1 /* write end of a pipe */
#define STDIN 0 /* file descriptor of standard in */
#define STDOUT 1 /* file descriptor of standard out */
int main()
{
int pid_1, /* will be process id of first child, which inverts the string */
pid_2; /* will be process id of second child, which converts the string to uppercase */
int fd[2]; //descriptor array for parent process
int fd2[2]; //descriptor array for first child process
int fd3[2]; //descriptor array for second child process
char ch [100]; //original character array
char ch2 [100]; //character array after reversal
int index = 0; //size
char character;
while((character = getchar()) != '\n') //get input and put it into array
{
ch[index] = character;
index++;
}
if(pipe (fd) == ERR)
{
perror("Parent pipe cannot be created\n");
exit (ERR);
}
if (pipe (fd2) == ERR) /* create a pipe */
{ /* must do before a fork */
perror ("Pipe cannot be created.\n");
exit (ERR);
}
if (pipe (fd3) == ERR) /* create a pipe */
{ /* must do before a fork */
perror ("Second pipe cannot be created.\n");
exit (ERR);
}
if ((pid_1 = fork()) == ERR) /* create 1st child */
{
perror ("Second process cannot be created.\n");
exit (ERR);
}
if (pid_1 != 0) /* in parent */
{
close(fd2[0]); //close read end of first child
close(fd[1]); //close write end of parent
printf("Parent process sends message %s\n", ch);
write(fd2[1], ch, sizeof(ch)); //write to write end of first child
close(fd2[1]); //close write end of first child
close(fd[0]);
if ((pid_2 = fork()) == ERR) /* create 2nd child */
{
perror ("Third process cannot be created.\n");
exit (ERR);
}
if (pid_2 != 0) /* still in parent */
{
wait ((int *) 0); /* wait for children to die */
wait ((int *) 0);
read(fd[0], ch2, sizeof(ch2)); //read read end of parent process
printf("Parent process receives message %s\n", ch2);
int i = 0;
while (i < index)
{
printf("%c", ch2[i]); //print message
i++;
}
printf("\n");
close(fd3[1]); //close write end of second child
close(fd[0]); //close read end of parent process
}
else /* in 2nd child */
{
close(fd3[1]); //close write end of second child
close(fd2[0]); //close read end of first child
read(fd3[0], ch2, sizeof(ch2)); //read read end of second child
printf("Second child receives %s\n", ch2);
int i = 0;
while (i < index)
{
ch2[i] = toupper(ch2[i]); //convert to uppercase
i ++;
}
printf("Second child sends message %s\n", ch2);
write(fd[1],ch2, sizeof(ch2)); //write to write end of parent process
close(fd3[0]); //close read end of second child
close(fd[1]); //close read end of parent process
}
}
else /* in 1st child */
{
close(fd2[1]); //close write end of first child
close(fd[0]); //close read end of parent process
read(fd2[0], ch, sizeof(ch)); //read read end of first child
printf("First child receives message %s\n", ch);
int i = 0;
while (i < index)
{
ch2[i] = ch[index - 1 - i]; //reverse
i++;
}
printf("First child sends message %s\n", ch2);
write(fd3[1], ch2, sizeof(ch2)); //write to write end of second child
close(fd3[1]); //close write end of second child
close(fd2[0]); //close read end of first child
}
exit(0);
}
Сначала попробуйте что-то более простое. – Beta
Не знаете, что вы имеете в виду, и как это исправить. Я попробовал следовать примеру, где он был всего одним ребенком и одним родителем, и работал, поэтому я просто добавил другого ребенка. Вероятно, я ошибаюсь. –
Хорошо, вы пытаетесь сразу несколько вещей; какой из них не удается? Есть ли сообщение об ошибке? Получает ли родительский процесс строку из пользователя? Получает ли первый ребенок через fd2? Правильно ли это вернет строку? Получает ли второй ребенок обратную строку через fd3? Правильно ли он изменил ситуацию? Получает ли родитель строку в верхнем регистре через fd? Можете ли вы изолировать то, что не работает? – Beta