I'm working on a C program to solve the Dining Philosophers' problem. I loop through 500 philosopher state changes, and output each philosophers' status on each interation with the following statement:
printf(" %d> |%s|%s|%s|%s|%s \n", i, get_state(phils[0]), get_state(phils[1]), get_state(phils[2]), get_state(phils[3]), get_state(phils[4]));
For context, here is the function get_state
, which converts a numeric philosopher status into a string:
char * get_state(int t) {
if (t == 1)
return " Thinking ";
if (t == 2)
return " Hungry ";
if (t == 3)
return " Eating ";
return "----Error----";
}
My problem is this: every 5-30 lines, one of them will start with the unicode character U+0001
. It appears that it is probably being inserted after the \n
of the previous line, but I can't tell what causes it at all!
I've provided a screenshot for clarity:
And here is the whole loop:
for (i = 1; i <= MAX; i++) {
silent = 0;
// receive message from child node
for (j = 0; j < PHIL_NO; j++) {
if(phils[j] == EATING) {
count[j]++;
}
lastPhils[j] = phils[j];
};
read(host[READ], &msg, sizeof(msg));
phils[msg.index] = msg.state;
for (j = 0; j < PHIL_NO; j++) {
if (phils[j] == lastPhils[j])
{
silent++;
}
};
printf("%4d> |%s|%s|%s|%s|%s \n", i, get_state(phils[0]), get_state(phils[1]),
get_state(phils[2]), get_state(phils[3]), get_state(phils[4]));
// if message is "hungry"
if (msg.state == HUNGRY) {
state_left = 0;
state_right = 0;
// check if chopsticks are available
if (phils[(msg.index - 1)%PHIL_NO] == EATING) {
state_left = 1;
}
if(phils[(msg.index + 1)%PHIL_NO] == EATING) {
state_right = 1;
}
// if available...
if (state_left+state_right == 0) {
// send message EATING to node
msg.state = EATING;
write(node[msg.index][WRITE], &msg, sizeof(msg));
} else {
// make the node wait
write(node[msg.index][WRITE], &msg, sizeof(msg));
}
} else if (msg.state == THINKING) {
// awake neighborhood nodes to eat
write(node[(msg.index-1)%PHIL_NO][WRITE], &msg, sizeof(msg));
write(node[(msg.index+1)%PHIL_NO][WRITE], &msg, sizeof(msg));
}
};
Edit: Oddly enough, when I run it in XTerm I can't see the extra character. I think that just means that XTerm doesn't display it. At this point, I'm pretty sure @Barmar is right in assuming it's one of my pipe write()
s misbehaving.