0

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!

2
Contributors
1
Reply
4
Views
4 Years
Discussion Span
Last Post by kordaff
0

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...
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.