gpt4 book ai didi

c - C语言中的生产者消费者错误

转载 作者:行者123 更新时间:2023-12-05 01:28:41 28 4
gpt4 key购买 nike

我试图在 C 中实现生产者消费者算法,以便 producer.cmydata.txt 文件中获取一个字符并将其放入 shell变量 DATA 然后 consumer.c 将从 DATA 中读取它并打印出来。输出必须采用相同的格式。一直以来,producer.cconsumer.c 在繁忙的循环中互相提供 TURN。

当我编译程序时,出现错误:error: too few arguments to function call, expected 1, have 0 because of both wait()职能。如果我做错了什么,请告诉我。我不确定您是否需要所有代码,但我希望这不会太多!

主.c:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "producer.c"
#include "consumer.c"

int main(){
char turn;
FILE *mydata = fopen("mydata.txt", "rt");

// Writing 0 into TURN.txt
FILE *TURN = fopen("TURN.txt", "wt");
if(TURN == NULL) exit(1);

putc('0', TURN);
fclose(TURN);

int pid = fork();

// Program done when turn == 'x'
while(turn - 'x' != 0){

TURN = fopen("TURN.txt", "rt");
turn = getc(TURN);
fclose(TURN);

// producer() uses pointer to mydata.txt, to avoid having to reopen in producer.c each time
if(pid == -1){ exit(1); }
if(pid == 0){ producer(mydata); wait(); }
if(pid != -1){ consumer(); wait(); }

}

fclose(mydata);

return 0;
}

生产者.c:

#include <stdio.h>
#include <stdlib.h>

void producer(FILE *mydata){
FILE *DATA;

// Writing 1 character from mydata.txt to DATA.txt
DATA = fopen("DATA.txt", "wt");
if(DATA == NULL) exit(1);
fprintf(DATA, "%c", getc(mydata));
fclose(DATA);

// Writing '1' into TURN.txt for consumer, or 'x' if done reading mydata.txt
FILE *TURN = fopen("TURN.txt", "wt");
if(TURN == NULL) exit(1);
if(!feof(mydata))
putc('1', TURN);
else
putc('x', TURN);
fclose(TURN);
}

消费者.c:

#include <stdio.h>
#include <stdlib.h>

void consumer(){

FILE *DATA;

DATA = fopen("DATA.txt", "r");
if(DATA == NULL) exit(1);
int c;
if(DATA == NULL) { exit(1); }
do {
c = fgetc(DATA);
if( feof(DATA) ) {
break ;
}
printf("%c", c);
} while(1);

fclose(DATA);

FILE *TURN = fopen("TURN.txt", "wt");
if(TURN == NULL) exit(1);
if(!feof(DATA))
putc('0', TURN);
else
putc('x', TURN);
fclose(TURN);

}

最佳答案

wait function正如错误告诉您的那样,需要一个参数。
准确地说,一个整数的地址。

关于c - C语言中的生产者消费者错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47626208/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com