我在使用信号量实现producent-consumer问题时遇到问题。 实际上,输出文件是100%正确 - 与输入文件相同。 虽然,在终端我得到疯狂的东西 like...
对我来说,看起来write函数总是返回值20,这就是为什么我不能打破while循环。 我一直在考虑解决方案几个小时,我找不到任何...... 如果你有任何想法,请帮助,作为一个新手是如此令人沮丧。
我的消费者代码:
while(1) {
block_sem(sem_FULL);
if(((counter = write(outputfile, rb->buffer[rb->tail], DATA_SIZE)) == DATA_SIZE)) {
printf("[c] %d bytes of data saved to the output file: %s\n", counter, rb->buffer[rb->tail]);
rb->tail = (rb->tail + 1) % BUF_SIZE;
unblock_sem(sem_EMPTY);
}
else if(counter < DATA_SIZE) {
printf("[c] %d bytes of data saved to the output file: %s\n", counter, rb->buffer[rb->tail]);
unblock_sem(sem_EMPTY);
break;
}
else if(counter == -1) {
perror("[c] could not write to the output file");
exit(EXIT_FAILURE);
}
}
我的制片人:
while((counter = read(inputfile, Data_in, DATA_SIZE))) {
if(counter == DATA_SIZE) {
block_sem(sem_EMPTY);
for(j=0; j<DATA_SIZE; j++) {
rb->buffer[rb->head][j] = Data_in[j];
}
printf("[p] %d bytes of data saved to the ring buffer: %s\n", counter, rb->buffer[rb->head]);
rb->head = (rb->head + 1) % BUF_SIZE;
unblock_sem(sem_FULL) }
if(counter < DATA_SIZE) {
block_sem(sem_EMPTY);
for(j=0; j<counter; j++) {
rb->buffer[rb->head][j] = Data_in[j];
}
rb->buffer[rb->head][counter] = '\0';
printf("[p] %d bytes of data saved to the ring buffer: %s\n", counter, rb->buffer[rb->head]);
unblock_sem(sem_FULL);
} }