Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reentrancy and Reentrant in C?

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?

like image 690
Koray Tugay Avatar asked Jun 05 '15 06:06

Koray Tugay


1 Answers

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.

like image 132
Sourav Ghosh Avatar answered Oct 15 '22 03:10

Sourav Ghosh