分享

为何中断处理程序中不能使用printf?

 黄南山 2018-04-11
An ISR should avoid calling non-reentrant functions. Some standard library functions are non-reentrant, such as many implementations of malloc and printf. Because interrupts can occur in the middle of task execution and because tasks might be in the midst of the "malloc" function call, the resulting behavior can be catastrophic if the ISR calls this same non-reentrant function.

---Real-Time Concepts for Embedded Systems

In general, within an interrupt service routine, you cannot call any routines that can potentially block waiting for resources. Nor would you really want to (think about it). The printf() routine can block on a semaphore trying to get access to output device until it becomes available. A workaround is to call logMsg(). The logMsg() routine works by queueing your message content via message queue. It is sent to logTask, which prints it out at a task level when logTask gets to run as deemed proper by the scheduler.



一个ISR应该避免调用不可重入函数。一些标准库函数是不可重入的,如经常实现的malloc和printf。因为中断可能发生在执行任务中,因为任务可能是在“malloc”的函数调用中,如果ISR调用此相同的不可重入函数,由此产生的行为可能是灾难性的。

不可重入函数是指这样的一类函数,不可以在它还没有返回就再次被调用。例如printf,malloc,free等都是不可重入函数。因为信号可能在任何时候发生,例如在printf执行过程中,因此不能在信号处理函数里调用printf,否则printf将会被重入。

函数不可重入大多数是因为在函数中引用了全局变量。例如,printf会引用全局变量stdout,malloc,free会引用全局的内存分配表。


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多