首页 文章

为什么我在Raspberry-Pi Jessie Lite上启动时无法访问stdin?

提问于
浏览
0

我有这个代码 . 我想要做的是等待用户按“q”结束程序 .

.
...starting few threads, which use fflush(stdout) (just saying...)
.
char n = 0;
while (n != 'q') {
    n = getchar(); //tried to use scanf() here as well
    printf("%c", n);
}
...killing all threads...
return 0;

当我运行这个 in a normal Linux enviroment it works fine. 当我在启动时在我的raspberry-pi上使用debian jessie lite发行版运行这个程序时出现问题(我将程序的路径添加到/etc/rc.local) - 它以无限循环结束, scanf 当我按 q 时,仍然会返回 -1getchar() 一些奇怪的字符并且程序不会结束 . Ctrl C也不起作用,所以没办法,如何结束程序 . 有什么建议? (至少如何杀死程序......?)

编辑:让你知道程序的功能 . 使用此程序的Raspberry-pi连接到某些串行端口,并转换和传输一些GPS数据 . 它应该工作"out of the box"没有任何键盘或鼠标或显示器 . = Just plug the device to some cables and do nothing more. 在某些情况下,有人希望在树莓上看到日志文件,所以他显然需要停止程序 .

编辑2:当我对一些普通的Raspbian做同样的事情时,它也运行得很好 .

Update:

我试图调试它 - 只将代码缩小到此

int main(void){
    char n=0;
    int x;
    while (n != 'q'){
        clearerr(stdin);
        x=scanf("%c",&n);
        printf("%c %d\n",n,x);
    }
    return 0;
}

service start udev 添加到rc.local并尝试了命令 update.rc.d udev enable

在启动时启动时,raspberry-pi的输出仍然是

-1
-1
-1
.
.

所以stdin肯定有问题 . 启动后和其他系统上,输出显然是 q 1 (当我按'q'(并输入)...)

当我试图从 /dev/tty 读取时, fopen() 返回 NULL

真的需要帮助

2 回答

  • 1

    编写此循环的惯用方法是:

    int c;
    while ((c = getchar()) != EOF && c != 'q'){
        putchar(c);
    }
    

    您的实现无法检测到文件结尾并将永远循环,打印有趣的字符,如 ÿ .

  • 0

    只是一个疯狂的猜测,stdin可能会重定向到其他东西,你需要直接从键盘读取 . 尝试以下代码:

    FILE *tty = fopen("/dev/tty", "r");
    if (!tty) {
        exit(1);
    }
    int n=0;
    while (n != 'q'){
        n=fgetc(tty); //tried to use scanf() here as well
        printf("%c",(char)n);
    }
    

相关问题