且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

重入和可重入用C?

更新时间:2022-10-30 23:19:04

我想补充什么先生的 @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 ***es 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.