fgets()是否锁定stdout从而防止printf [英] Does fgets() locks stdout preventing printf

查看:202
本文介绍了fgets()是否锁定stdout从而防止printf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个线程的C程序,这些线程之一几乎一直被阻塞在fgets()中,等待用户输入.第二个线程可能需要打印到终端,而第一个线程在fgets()上被阻止.

I have a C program with two threads one of those threads is almost all the time blocked in a fgets() waiting for user input. The second thread may need to print to the terminal while the first one is blocked on fgets().

从我的测试看来,该程序等待第一个线程上的fgets()返回,然后第二个线程可以打印.

From my tests it seems that the program waits for the fgets() on the first thread to return and then the second thread can print.

这是它的工作对象,还是在fgets()上另一个线程被阻塞时我可以打印?

Is this who it works or could I print while the the other thread is blocked on the fgets()?

此实现在eCos(嵌入式可配置操作系统)上运行.

This implementations runs on eCos (embedded Configurable operating system).

线程已锁定在fgets():

int my_getline (char** argv, int argvsize)
{
    static char line[MAX_LINE];
    char *p;
    int argc;

    fgets(line, MAX_LINE, stdin);


    for (argc=0,p=line; (*line != '\0') && (argc < argvsize); p=NULL,argc++) {
        p = strtok(p, " \t\n");
        argv[argc] = p;
        if (p == NULL) return argc;
    }
    argv[argc] = p;
    return argc;
}

尝试打印的线程:

while(1){
        unsigned char bufr[50];
        read_until(bufr);
        if (bufr[1] == (unsigned char)NMFL ){
            cyg_mutex_lock(&scree_mtx);
            printf("Memory half full!\n");
            cyg_mutex_unlock(&scree_mtx);
            continue;
        }
        cyg_mbox_put( mbx_serial_userH, bufr );     
}

输出(我确定该消息之前已经存在):

Output (I'm sure the message was there before):

推荐答案

C标准根本没有指定标准输入流和标准输出流之间的任何关联.特别是,它没有指定一个线程通过任何标准函数从标准输入读取时阻塞应该导致任何输出函数阻塞.

The C standard does not specify any association at all between the standard input stream and the standard output stream. In particular, it does not specify that one thread blocking on reading from standard input, via any standard function, should cause any output function to block.

但是,该标准也没有相反的说法,即在stdin的输入输入上阻塞的线程一定不会导致另一个在stdout的输出上阻塞的线程.是否发生这种情况将取决于C实现,并且可能取决于stdinstdout与之关联的特定设备.

HOWEVER, the standard also does not say the opposite, that a thread blocking on input input from stdin must not cause another to block on output to stdout. Whether that happens would be a function of the C implementation, and probably of the specific devices with which stdin and stdout are associated.

您似乎正在使用Windows C实现,并且将stdinstdout都连接到CMD.EXE窗口. Windows有很多特质,我倾向于猜测您观察到的阻止就是其中之一.我不希望在Linux或OSX上出现相同的情况,但这并不意味着它是错误的.

You appear to be using a Windows C implementation with stdin and stdout both connected to a CMD.EXE window. Windows has a lot of idiosynchrasies, and I'm inclined to guess that the blocking you observe is one of them. I would not expect the same on Linux or OSX, but that does not mean it is erroneous.

这篇关于fgets()是否锁定stdout从而防止printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆