c - Printf 中的额外 \1 个字符
问题描述
我正在开发一个 C 程序来解决餐饮哲学家的问题。我循环遍历 500 个哲学家状态变化,并使用以下语句在每次交互中输出每个哲学家的状态:
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]));
对于上下文,这里是函数get_state
,它将数字哲学家状态转换为字符串:
char * get_state(int t) {
if (t == 1)
return " Thinking ";
if (t == 2)
return " Hungry ";
if (t == 3)
return " Eating ";
return "----Error----";
}
我的问题是:每 5-30 行,其中一行将以 unicode 字符开头U+0001
。看来它可能是\n
在上一行之后插入的,但我根本不知道是什么原因造成的!
这是整个循环:
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));
}
};
编辑:奇怪的是,当我在 XTerm 中运行它时,我看不到多余的字符。我认为这只是意味着 XTerm 不显示它。在这一点上,我很确定@Barmar 认为这是我的管道write()
行为不端之一是正确的。
解决方案
推荐阅读
- ruby-on-rails - 如何在 RSPEC 中测试链调用?
- php - 在laravel中bcrypt密码后我无法登录
- c# - 如何在 asp.net core 中设置用户特定的会话超时
- javascript - 在反应中读取与跨站点资源关联的cookie
- docker - 如何调试 Telegraf 为什么不将数据从 MQTT 发送到 influxdb
- google-cloud-sql - Google Cloud SQL 上的 PostgREST:unix 套接字 URI 格式?
- flutter - 转换为类型类 dart http 响应体
- java - 依赖关系引入了一个传递库,该库使用 TIFF 文件破坏 ImageIO.read
- java - 如何从处理器内的 Apache Camel 中的路由获取响应并在处理器内调用该路由?
- groovy - Spock-在被测类的私有方法调用中捕获方法参数