重入和可重入用C? [英] Reentrancy and Reentrant in C?

查看:237
本文介绍了重入和可重入用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了一本书叫的Linux系统编程。从这本书中引用:


  

有关系统调用等库函数是什么?如果你的
  过程是写入文件或分配内存的中间,
  和信号处理程序写入到同一文件或还调用的malloc()?
  有些功能显然不是折返。如果程序是在
  执行一个不可重入功能的中间和一个信号发生和
  信号处理程序然后调用同一个不可重入函数,混沌
  可随之而来。


但随后将遵循:


  

保证折返功能


  
  

保证是安全的重入功能在信号使用


  
  

在这里的一些功能。


  
  

写()


  
  

在这里的一些功能。


我很困惑,是的write()折返,还是不行?因为我觉得它的声明相冲突:


  

如果你的过程是什么书面的中间文件?



解决方案

我想补充什么先生的 @Joachim Pileborg 已经在他的答案当按照维基条目的重入的,一个函数的基本规则是重入是


  1. 折返code不得持有任何静态(或全球)的非恒定的数据。

  2. 折返code不得修改自己的code。

  3. 折返code不能调用非重入计算机程序或程序。

要阐述的功能,如果折返,不会有任何问题,它的的实施的(诱导它使用自己内部数据结构),无论是从不同的上下文中被调用。

被提供给该功能的参数,(如一个文件描述符)不影响它的重入。

因此​​,的write(),函数本身是可重入的,但如果所谓的来自不同的线程相同的文件描述符,这显然会产生错误的结果。再次,这并不意味着,在重入写()不见了。它的折返的,但不是线程安全的,而这两个是不同的方面。

I am reading a book called Linux System Programming. Quoting from this book:

What about system calls and other library functions? What if your process is in the middle of writing to a file or allocating memory, and a signal handler writes to the same file or also invokes malloc()? Some functions are clearly not reentrant. If a program is in the middle of executing a nonreentrant function and a signal occurs and the signal handler then invokes that same nonreentrant function, chaos can ensue.

But then it will follow:

Guaranteed-Reentrant Functions

Functions guaranteed to be safely reentrant for use in signals

some functions here..

write()

some functions here..

I am confused, is write() reentrant, or not? Because I think it clashes with the statement:

What if your process is in the middle of writing to a file?

解决方案

Just to add what Mr. @Joachim Pileborg already mentioned in his answer, as per the wiki entry for Reentrancy, the basic rules for a function being re-entrant are

  1. Reentrant code may not hold any static (or global) non-constant data.
  2. Reentrant code may not modify its own code.
  3. Reentrant code may not call non-reentrant computer programs or routines.

To elaborate, the function, if reentrant, will not have any issue with its own implementation (inducing the internal data structures it uses for itself) whether being called from different context.

A parameter, (such as a file descriptor) which is supplied to the function does not affect it's reentrancy.

So, for write(), the function itself is Reentrant, but if called with same file descriptor from different thread, it will obviously produce erroneous result. Again, that does not mean, the Reentrancy of write() is gone. It is Reentrant, but not thread-safe, and these two are different aspects.

这篇关于重入和可重入用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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