What happens when a process is forked?

fork, linux, perl, posix, unix

Solution

To answer the nominal question, since you commented that the accepted answer fails to do so, `fork` affects the process in which it is called. In your example of rTorrent spawning a Perl process which then calls `fork`, it is the Perl process which is duplicated, since it was the Perl process which called `fork`.

In the general case, there is no way for a process to `fork` any process other than itself. If it were possible to tell another arbitrary process to go `fork` itself, that would open up no end of security and performance issues.

Problem

I've read about fork and from what I understand, the process is cloned but which process? The script itself or the process that launched the script? For example: I'm running rTorrent on my machine and when a torrent completes, I have a script run against it. This script fetches data from the web so it takes a few seconds to complete. During this time, my rtorrent process is frozen. So I made the script fork using the following ``` my $pid = fork(); if ($pid == 0) { blah blah blah; exit 0; } ``` If I run this script from the CLI, it comes back to the shell within a second while it runs in the background, exactly as I intended. However, when I run it from rTorrent, it seems to be even slower than before. So what exactly was forked? Did the rtorrent process clone itself and my script ran in that, or did my script clone itself? I hope this makes sense.

Original source