我遇到以下代码问题。我在使用forks(创建进程)进行实验室分配。它是一个简单的程序,它应该从键盘读取输入,然后将其读/写到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);
}
}
答案 0 :(得分:4)
这一行(例如)不会按照您的想法行事:
if(fd = open(FifoName, O_WRONLY) == -1)
等于运算符的赋值运算符高precedence,所以你所做的就是这样:
if(fd = (open(FifoName, O_WRONLY) == -1))
如果你想要这个:
if((fd = open(FifoName, O_WRONLY)) == -1)
缓冲区读/写的问题是因为你写了整个缓冲区:
size_written = write(fd, buff, sizeof(buff));
更改为仅使用strsize
编写实际字符串。