【发布时间】:2020-04-30 07:51:58
【问题描述】:
我必须编写两个独立的程序,一个是生产者,第二个是消费者(都在不同的终端中运行)。我向 Producer 提供了一个参数,该参数可以是文本或单个字符。然后,生产者创建一个.txt 文件,将单个字符放入其中,然后将其关闭。消费者打开该文件,读取该字符并将其打印在终端上,然后关闭该文件并将其删除。整个过程不断重复。如果提供的参数包含*,例如* 或text*,它将完成这两个程序,在结束前打印*。我只能使用函数:open()、close()、read()、write()、unlink()。预期结果如下所示:
这两个代码我都写了,这是生产者代码:
(我知道我不必要地定义了SIZE并使用了它,请不要介意)
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#define SIZE 1
int main(int argc, char *argv[]){
char buff;
do{
int fdi=-1;
while(fdi<0){
fdi=open("test.txt",O_WRONLY | O_CREAT | O_EXCL, 0666);
}
read(STDIN_FILENO,&buff,SIZE);
write(fdi,&buff,SIZE);
close(fdi);
}while(buff!='*');
return 0;
}
这是消费者代码:
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#define SIZE 1
int main(int argc, char *argv[]){
char buff;
do{
int fdi=-1;
while(fdi<0){
fdi=open("test.txt",O_RDONLY | O_EXCL);
}
int rdin=read(fdi,&buff,SIZE);
if(rdin>0){
write(STDOUT_FILENO,&buff,SIZE);
close(fdi);
unlink("test.txt");
}
else{
close(fdi);
}
}while(buff!='*');
return 0;
}
我的问题是:Producer 程序如何在文件中插入多个字符?我的意思是,如果我只运行 Producer 程序,并提供参数text,它只会在文件中插入字母t,其余的将插入到其他文件中。它不应该循环并将整个text 单词添加到一个文件中吗?没有任何声明保证文件将包含一个字符,但它只包含一个字符,我不知道为什么。
【问题讨论】:
-
你怎么知道
text中的哪个t被写入了文件? -
read(STDIN_FILENO,&buff,SIZE);中的SIZE是什么?那会读多少个字符? -
@ScottHunter 我只是在其他终端运行“cat test.txt”,然后运行“rm test.txt”,我可以看到文件“t->e->x-> 中的字母发生了变化t"
-
@DavidC.Rankin 它是 buff 的大小,我在帖子中写道,我知道我不必要地定义它并且可能只写 1(因为 char 大小为 1 字节)
-
#define是个好东西,评论是为了回应“Producer 程序怎么不会在文件中插入一个以上的字符?”
标签: c linux file producer-consumer