Hi There,
I have an embarrassing problem with fifo.. I have to write two programs, named write and read. The write program has to copy a plain text file to stdout and the read program has to read the stdin then count number of bytes in the stream. It is a process synchronization problem, the way I approach it is by fifo.. Then I made these programs as following..
write.c
Code:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
char *fifo = "fifo";
int main() {
FILE *fp;
char *buffer;
int fd, nwrite;
unsigned long length;
if((fp = fopen("test.txt", "r")) < 0) {
printf("write-main: cannot open test.txt\n");
}
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fseek(fp, 0, SEEK_SET);
// Allocate memory
buffer = (char *)malloc(length+1);
if(!buffer) {
printf("write-main: memory error\n");
fclose(fp);
return;
}
// Read file content into buffer
fread(buffer, length, 1, fp);
fclose(fp);
if(mkfifo(fifo, 0666) == -1) {
printf("write-main: cannot create fifo\n");
} else {
if((fd = open(fifo, O_WRONLY | O_NONBLOCK)) < 0) {
printf("write-main: fifo open failed\n");
} else {
if((nwrite = write(fd, buffer, length)) == -1) {
printf("write-main: message write failed\n");
}
}
}
}
read.c
Code:
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#define MSGSIZE 100
char *fifo = "fifo";
int main() {
FILE *fp;
unsigned long length;
char *buffer;
int fd;
if((fd = open(fifo, O_RDWR)) < 0) {
printf("read-main: cannot open fifo\n");
} else {
if((read(fd, buffer, length)) < 0) {
printf("read-main: message read failed\n");
}
}
printf("message recieve:%s\n", buffer);
}
These two programs compile perfectly, but when i try to run it.. It shows the "write-main: fifo open failed" which means it couldn't open the fifo that created at runtime.. I made these two programs since I thought that fifo is the best way to tackle this problem, is there any other suggestion how to solve this? Thank you...