Я отправляю данные из процесса отправителя в процесс получателя с использованием Pipes. Проведя некоторое количество времени, пытаясь решить эту проблему, все еще не могу понять это.Неверные данные, возвращаемые при чтении из трубы
Письмо на трубу работает, но при чтении с трубы я получаю «ничего». Ниже приведен код и вывод. Для простоты я читаю только первый байт (один алфавит) из трубы.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void GenerateData();
void WriteData();
void ReadData();
int fildes[2];
char* buff;
char* alphab;
char* alphabt;
int i, n;
int pid_rcv = -1;
main(int argc, char** argv)
{
buff = (char*) malloc(26);
pipe(fildes); //pipe with two file descriptors (for write and read)
printf("---IPC---\n");
printf("Pipe_in descrp: %i\n", fildes[1]);
printf("Pipe_out descrp: %i\n", fildes[0]);
//Generate alphabets A - Z
GenerateData();
//Fork child (receiver). Parent will be sender
pid_rcv = fork();
if(pid_rcv < 0)
{
/* check for error while forking */
fprintf(stderr, "Fork failed.\n");
exit(-1);
}
else if (pid_rcv == 0)
{
/* this is the receiver process */
printf("Receiver's PID: %i\n", getpid());
close(fildes[1]); //close write end of pipe
ReadData(); //read then print alphabet from pipe
exit(0); //exit receiver
}
else
{
/* this is the sender process */
printf("Sender's PID: %i\n", getpid());
close(fildes[0]); //close read end of pipe
WriteData(); //write alphabets to pipe at 1 sec intervals
//close(fildes[1]); //close write pipe
wait(NULL); //wait for receiver process to finish
}
//terminate
free(buff);
printf("End of IPC program.\n");
return 0;
}
void GenerateData()
{
//ASCII letters from A to Z. Buffer size of 26
n = 65;
for(i=0; i<26; i++)
{
buff[i] = (char) n;
n++;
}
//display generated data
printf("Buffer: ");
for(i=0; i<26; i++)
{
printf("%c", (char) buff[i]);
}
printf("\n");
}
void WriteData()
{
printf("Writing data to pipe...\n");
alphab = (char*) malloc(1);
for(i=25; i>=0; i--) //reverse order
{
alphab[0] = (char) buff[i];
write(fildes[1], &alphab, sizeof(char)); //write an alphabet to pipe
printf("%c", alphab[0]);
sleep(1);
}
printf("\nDone writing data to pipe.\n");
free(alphab);
}
void ReadData()
{
int numbBytes;
printf("Attempting to read data from pipe...\n");
alphabt = (char*) malloc(sizeof(char));
numbBytes= read(fildes[0], alphabt, sizeof(char));
printf("Number of bytes read=%d\n", numbBytes);
printf("Read data: %c\n", (char) *alphabt);
free(alphabt);
}
---IPC---
Pipe_in descrp: 4
Pipe_out descrp: 3
Buffer: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Sender's PID: 5195
Writing data to pipe.
ZYXWVUTSRQPONMLKJIHGFEDCBA
Done writing data to pipe.
Receiver's PID: 4842
Attempting to read data from pipe...
Number of bytes read=1
Read data: 0
End of IPC program.
Спасибо! Очень глупая ошибка с моей стороны. Еще раз спасибо. Выход теперь: 'ZYXWVUTSRQPONMLKJIHGFEDCBA' – nikk