循环应该中断,但它一直卡在fgets
. 通过管道process_P1
交谈。inputHandler
问题是inputHandler
没有意识到什么时候停止写作......永远不会达到process_P1
'lalala' 。printf
void process_P1(char *argv[], int fd[2], pid_t child)
{
int bytes = 0;
static char bufferIn[BUFFER_SIZE];
static char bufferOut[BUFFER_SIZE];
char line[BUFFER_SIZE];
// close reading end of pipe
close(fd[0]);
FILE *in = fopen(getInput(argv), "r");
FILE *out = fdopen(fd[1], "w");
if (in == NULL) {
sys_err("fopen(r) error (P1)");
}
int ret = setvbuf(in, bufferIn, _IOLBF, BUFFER_SIZE);
if (ret != 0) {
sys_err("setvbuf error (P1)");
}
if (out == NULL) {
sys_err("fdopen(w) error (P1)");
}
ret = setvbuf(out, bufferOut, _IOLBF, BUFFER_SIZE);
if (ret != 0) {
sys_err("setvbuf error (P1)");
}
while (fgets(line, BUFFER_SIZE, in) != NULL)
{
fprintf(out, "%s", line);
bytes += count(line) * sizeof(char);
}
// alert P2 to stop reading
//fprintf(out, "%s", STOP);
fclose(in);
fflush(out);
fclose(out);
printf("P1: file %s, bytes %d\n", getInput(argv), bytes);
// wait P2 ends
if (waitpid(child, NULL, 0) < 0) {
sys_err("waitpid error (P1)");
}
}
void *inputHandler(void *args)
{
int ret;
static char bufferIn[BUFFER_SIZE];
char line[BUFFER_SIZE];
struct node *iterator;
int *fd = (int*)args;
close(fd[1]);
FILE *in = fdopen(fd[0], "r");
if (in == NULL) {
sys_err("fdopen(r) error (P2)");
}
ret = setvbuf(in, bufferIn, _IOLBF, BUFFER_SIZE);
if (ret != 0) {
sys_err("setvbuf(in) erro (P2)");
}
while (fgets(line, BUFFER_SIZE, in) != NULL)
{
// printf("%s", line);
iterator = firstArg;
while (iterator->next != NULL)
{
ret = sem_wait(&(iterator->sem));
if (ret == 0) {
strcat(iterator->buffer, line);
} else {
sys_err("sem_wait error");
}
ret = sem_post(&(iterator->sem));
if (ret != 0) {
sys_err("sem_post error");
}
iterator = iterator->next;
}
line[0] = '\0';
}
printf("lalala\n");
iterator = firstArg;
while (iterator->next != NULL)
{
ret = sem_wait(&(iterator->sem));
if (ret != 0) {
sys_err("sem_wait error");
}
iterator->shouldStop = 1;
ret = sem_post(&(iterator->sem));
if (ret != 0) {
sys_err("sem_post error");
}
iterator = iterator->next;
}
fclose(in);
return NULL;
}