Posts Tagged ‘write

Locking Files in PHP

PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of  locking or it will not work). If there is a possibility that more than one process could write to a file at the same time then the file should be locked.

flock() operates on fp which must be an open file pointer. operation is one of the following:

  1. To acquire a shared lock (reader), set operation to LOCK_SH
  2. To acquire an exclusive lock (writer), set operation to LOCK_EX
  3. To release a lock (shared or exclusive), set operation to LOCK_UN
  4. If you don’t want flock() to block while locking, add LOCK_NB to LOCK_SH or LOCK_EX

When obtaining a lock, the process may block. That is, if the file is already locked, it will wait until it gets the lock to continue execution. flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows). flock() returns TRUE on success and FALSE on error (e.g. when a lock could not be acquired).

Here is a script that writes to a log file with the fputs function and then displays the log file’s contents:

<?php

$fp = fopen(“/tmp/log.txt”, “a”);

flock($fp, LOCK_EX); // get lock

fputs($fp, date(“h:i A l F dS, Y\n”)); // add a single line to the log file

flock($fp, LOCK_UN); // release lock

fclose($fp);

echo “<pre>”; // dump log

readfile(“/tmp/log.txt”);

echo “</pre>\n”;

?>

 

Tags : , , , , , , , ,

Memory errors in C : Terminology

Using terminology from SafeC, memory errors in C programs can be classifieds into two different types:

  1. Spatial memory errors and
  2. Temporal memory errors.

Spatial memory errors in C programs include array bounds violations (i.e., buffer overrun) errors, uninitialized pointer dereferences (causing an access to an invalid address), invalid type conversion errors, format string errors, etc. Temporal memory errors include uses of pointers to freed heap memory and uses of pointers to an activation record after the function invocation completes.

Here we focus on detecting uses of pointers to freed heap memory. In previous work, we have described techniques for detecting spatial errors with very low overhead, which also exploits Automatic Pool Allocation to reduce run-time overhead. Those techniques (and other approaches that detect spatial errors) are complementary to our approach here because our approach here does not use any metadata on individual pointers or objects and does not restrict adding such metadata. For dangling pointer accesses to stack objects, some combination of compile time escape analysis, run-time checks, or converting possibly escaping stack allocations to heap allocations can be used. By dangling pointer errors we mean use of pointers to freed heap memory, where use of a pointer is a read, write or free operation on that pointer.

Tags : , , , , , , , , , , ,