Skip to content

Instantly share code, notes, and snippets.

@Aeon
Last active December 14, 2015 07:59
Show Gist options
  • Save Aeon/5054394 to your computer and use it in GitHub Desktop.
Save Aeon/5054394 to your computer and use it in GitHub Desktop.
forking and db resources and postgres

anyway what happens is

  • parent opens db connection $db
  • parent forks child worker, which inherits the connection resource
  • child worker does some work and exits (successfully or not)
  • php cleans up any open resource handles, $db among them.
  • parent thinks $db is still a valid resource.
  • parent tries to access it, or parent forks a new child and gives it the invalid handle...
  • php goes boom, because it tries to use an invalid connection resource.

solution?

make sure to open your db connections explicitly in the child worker. Things are worse if you are using a singleton such as above, because the db connection is hidden from you and you are not even aware that it was reused, so you have to explicitly close the connection in the worker constructor before calling Database::query() for example.

<?php
class Database {
private static $dbh = NULL;
public static function query() {
$dbh = self::getConnection();
// ... process query/args
$result = pg_prepare($dbh, $query_name, $sql);
$result = pg_execute(self::getConnection(), $query_name, $args);
return $result;
}
public static function getConnection() {
if(self::$dbh === NULL || pg_connection_status(self::$dbh) !== PGSQL_CONNECTION_OK)
{
$db_conn = pg_connect(join(' ', $connection_params));
self::$dbh = $db_conn;
}
return self::$dbh;
}
public static function close() {
pg_close(self::$dbh);
self::$dbh = NULL;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment