from typing import Optional
import fcntl


def safe_read_file(file: str) -> Optional[str]:
    """
    Safely read a file by acquiring a shared lock to prevent other processes
    from writing to it while reading.
    """
    try:
        file_obj = open(file, "r")
    except FileNotFoundError:
        return None

    try:
        # acquire a shared lock on the state file, which is blocking until we can lock it
        fcntl.lockf(file_obj.fileno(), fcntl.LOCK_SH)

        try:
            return file_obj.read()
        finally:
            fcntl.flock(file_obj.fileno(), fcntl.LOCK_UN)
    finally:
        file_obj.close()