AV-2 has asked for the wisdom of the Perl Monks concerning the following question:

Good day monks, I have a script that at some point attempts to do something in the spirit of:
use DBI; use strict; use warnings; my $db = DBI->connect(qq/dbi:SQLite:dbname=test/); my $pid = fork(); $db->do("DROP TABLE IF EXISTS foo"); waitpid($pid,0); $db->disconnect;
Basically it is a script that creates a database handler. Then, at some point, after testing several conditions it might fork. After forking, it will attempt to access the database, but I get an error. It warns me that the handle number x is owned by the thread y, not current z thread, and handles can't be shared. Then it suggests me that somehow performing a clone on the db handler will somehow, magically solve my problem. I have tried using clone on several ways, but I don't have too much experience with fork. In fact, this is the first time I am using it, to avoid enclosing half of my script in a loop that will only execute two times. I appreciate all the help you can give me.

Replies are listed 'Best First'.
Re: DBI handler after perfoming fork?
by jasonk (Parson) on Apr 12, 2008 at 02:35 UTC

    Trying to share the database handle between two processes like you are doing is just asking for trouble. The best solution would be to connect to the database after the fork, or at least have the child process reconnect to the database after the fork.

    You also need to read up on what happens when the process forks, because with the example code you have posted, the next step after the fork is that both the parent and child process are going to attempt to drop the 'foo' table, and then they are both going to call waitpid, and then both attempt to disconnect from the database.


    www.jasonkohles.com
    We're not surrounded, we're in a target-rich environment!
      I see. I will make it make a new connection to the database then. I really would have preferred not to do so, but oh well. And yeah, I wrote that code kinda too fast and forgot to add the exit for the child.
Re: DBI handler after perfoming fork?
by kyle (Abbot) on Apr 12, 2008 at 04:43 UTC

    You might find it useful to look at DBI, fork, and clone.

    It looks as if your fork is creating threads, which would indicate to me that you're on Windows. I don't know if this will make a difference, but I'm a little less confident that the "fork and clone" described will perform as advertised. Still, it may be worth looking at, if that's the route you want.