I am trying to figure out how to use fork() with exec(). I read through the perl docs on how it works, but I can't figure out how to implement it.

For example if I wanted to fork a custom sh script:

if (this_condition is true) {
    $mypid = fork(); ##?? not sure how this actually works
    exec("my_custom.sh > my_custom_output.txt"); ## is this affected by the fork or what do I do?
}

Every example I've seen creates a $mypid = fork(), but I don't know how it actually works and if this is what I'm really wanting to do do.

Thank you!

The child process gets a pid of 0, the parent process gets a new pid that is not equal to zero. You'll probably only want to run the exec once, in either the child process from fork, or in the parent. All the code after fork() runs in each process, unless it was unsuccessful then pid will be undefined.

Put your exec where you want it to run, in the child process section, or in the parent process section:

if (this_condition is true) 
{
$mypid = fork(); ##?? not sure how this actually works

if (! $mypid)
{
# put your exec here to run in the child process.
}
elsif (undef $mypid)
{
# fork() failed.
}
else
{
# put exec here to run in the parent process
}
# you may want to exit one or both processes somewhere in 
this block too...
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.