我在使用以下代码时遇到问题。我正在做一个关于使用分叉(创建进程)的实验室任务。它是一个简单的程序,应该从键盘读取输入,然后将其读/写到 fifo 并显示其内容和写入的字节。
当我运行它时,一切似乎都很好,直到我输入一些文本。父打印消息显示正常,但子打印消息从未出现,直到我输入我的第二条消息,它总是说它写了 80 个字节,即使我知道它没有,还有一堆奇怪的特殊字符无处不在。
以下是有关程序应如何运行的可执行文件: Linux:http ://www.mediafire.com/? 6806v24q6lz7dpc QNX:http ://www.mediafire.com/?a9dhiwmrlx2ktkp
到目前为止我的代码:
#include<stdio.h>
#include<stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char *argv[]) {
char FifoName[] = "fifoDan";
int fd;
pid_t retval;
int size_read;
char buff[80];
int size_written;
mknod(FifoName, S_IFIFO | 0666, 0);
// Check if its not equal to zero (ie: child process = 0)
if (retval = fork ()) {
printf ("Parent: Waiting for writers \n");
if(fd = open(FifoName, O_RDONLY) == -1) {
perror( "Could not read the FIFO" );
return EXIT_FAILURE;
}
printf ("Parent: Received a writer \n");
do {
int strsize;
size_read = read(fd, buff, sizeof(buff));
printf("Parent: read %d bytes: %s \n", size_read, buff);
fflush(stdout);
strsize = strlen(buff);
// put a '\0' at the end of the data
buff[strsize] = '\0';
} while(size_read > 0);
close(fd);
waitpid(retval, NULL, NULL);
if(unlink(FifoName) != -1) {
return EXIT_SUCCESS;
} else {
return EXIT_FAILURE;
}
} else {
printf ("Child pid %d waiting for readers \n", getpid ());
fflush(stdout);
if(fd = open(FifoName, O_WRONLY) == -1) {
perror( "Could not read the FIFO" );
return EXIT_FAILURE;
}
printf ("Child: Got a reader, enter some stuff:\n");
fflush(stdout);
while(fgets(buff, 80, stdin) != NULL) {
int strsize;
strsize = strlen(buff);
if(strsize < 80) {
buff[strsize] = '\0';
}
size_written = write(fd, buff, sizeof(buff));
printf ("Child: wrote %d bytes \n", size_written);
fflush(stdout);
}
close(fd);
}
}