diff --git a/src/backend/nodes/gen_node_support.pl b/src/backend/nodes/gen_node_support.pl
index 41d824870b..4a7902e6bf 100644
--- a/src/backend/nodes/gen_node_support.pl
+++ b/src/backend/nodes/gen_node_support.pl
@@ -34,6 +34,8 @@ sub elem
 	return grep { $_ eq $x } @_;
 }
 
+# output file names
+my @output_files;
 
 # collect node names
 my @node_types = qw(Node);
@@ -450,6 +452,7 @@ my $header_comment =
 
 # nodetags.h
 
+push @output_files, 'nodetags.h';
 open my $nt, '>', 'nodetags.h' . $tmpext or die $!;
 
 printf $nt $header_comment, 'nodetags.h';
@@ -476,9 +479,13 @@ foreach my $infile (sort @ARGV)
 
 # copyfuncs.c, equalfuncs.c
 
-open my $cff, '>', 'copyfuncs.funcs.c' . $tmpext   or die $!;
-open my $eff, '>', 'equalfuncs.funcs.c' . $tmpext  or die $!;
-open my $cfs, '>', 'copyfuncs.switch.c' . $tmpext  or die $!;
+push @output_files, 'copyfuncs.funcs.c';
+open my $cff, '>', 'copyfuncs.funcs.c' . $tmpext or die $!;
+push @output_files, 'equalfuncs.funcs.c';
+open my $eff, '>', 'equalfuncs.funcs.c' . $tmpext or die $!;
+push @output_files, 'copyfuncs.switch.c';
+open my $cfs, '>', 'copyfuncs.switch.c' . $tmpext or die $!;
+push @output_files, 'equalfuncs.switch.c';
 open my $efs, '>', 'equalfuncs.switch.c' . $tmpext or die $!;
 
 printf $cff $header_comment, 'copyfuncs.funcs.c';
@@ -664,9 +671,13 @@ close $efs;
 
 # outfuncs.c, readfuncs.c
 
-open my $off, '>', 'outfuncs.funcs.c' . $tmpext   or die $!;
-open my $rff, '>', 'readfuncs.funcs.c' . $tmpext  or die $!;
-open my $ofs, '>', 'outfuncs.switch.c' . $tmpext  or die $!;
+push @output_files, 'outfuncs.funcs.c';
+open my $off, '>', 'outfuncs.funcs.c' . $tmpext or die $!;
+push @output_files, 'readfuncs.funcs.c';
+open my $rff, '>', 'readfuncs.funcs.c' . $tmpext or die $!;
+push @output_files, 'outfuncs.switch.c';
+open my $ofs, '>', 'outfuncs.switch.c' . $tmpext or die $!;
+push @output_files, 'readfuncs.switch.c';
 open my $rfs, '>', 'readfuncs.switch.c' . $tmpext or die $!;
 
 printf $off $header_comment, 'outfuncs.funcs.c';
@@ -962,10 +973,26 @@ close $ofs;
 close $rfs;
 
 
-# now rename the temporary files to their final name
-foreach my $file (
-	qw(nodetags.h copyfuncs.funcs.c copyfuncs.switch.c equalfuncs.funcs.c equalfuncs.switch.c outfuncs.funcs.c outfuncs.switch.c readfuncs.funcs.c readfuncs.switch.c)
-  )
+# now rename the temporary files to their final names
+foreach my $file (@output_files)
 {
 	Catalog::RenameTempFile($file, $tmpext);
 }
+
+
+# Automatically clean up any temp files if the script fails.
+END
+{
+	# take care not to change the script's exit value
+	my $exit_code = $?;
+
+	if ($exit_code != 0)
+	{
+		foreach my $file (@output_files)
+		{
+			unlink($file . $tmpext);
+		}
+	}
+
+	$? = $exit_code;
+}
