Largely used GPF codes are of three types :
- 0 is success (all other values indicate a failure).
 - 2 is usually used for unxpected errors.
 - 1 for things like a BAD signature.
 
 The proper way to identify an error is by interpreting the output of --status-fd--status-fd <file descriptor> or --status-file <filename>.
Now for the particular Question that you are using, there might be two reasons :
- GPG is asking whether you want to continue on with the encryption using an unsigned key. Since no user can input Y it produces an error.
 
To fix this provide the following switches :
    --yes and --always-trust
- It may also be a permission problem. gpg is trying to access a directory that it can't have access to, so it fails with a fatal error. (error code 2)
 
You can fix that by specifying a homedir directive with a directory writable by gpg. Like this:
   $cmd = "/usr/bin/gpg -a --recipient $to -e -o $outfile $infile --homedir /path/to/dir";
Information from man gpg:
   --homedir directory
   Set the name of the home directory to directory
    If this option is not used it defaults to "~/.gnupg". It does not make sense to    use     this in a options file. This also overrides the environment variable $GNUPGHOME.
You can also use this link to know more about this one.