http://qs1969.pair.com?node_id=11151325

cavac has asked for the wisdom of the Perl Monks concerning the following question:

I played around with ChatGPT today and got it to generate me a Perl script that forks children and restarts any that failed. Here's my initial prompt:

Write a Perl program that forks 5 child processes. The main process should handle SIGCHILD and restart any child processes that have exite +d. The child processes have a function called "doWork" that have a "Your code here" comment.

There was a bit back-and-forth to fix some bugs and to get ChatGPT to "use English". On the plus side, ChatGPT used "use strict; use warnings;" right from the start AND used readable indenting as well(*). Here's what it came up with:

Edit: Copied an old version at first, this is now the latest version

use strict; use warnings; use English qw( -no_match_vars ); use POSIX qw( :sys_wait_h ); # Fork 5 child processes my $num_processes = 5; for (my $i = 0; $i < $num_processes; $i++) { my $pid = fork(); if ($pid == 0) { # Child process doWork(); exit; } elsif (!defined $pid) { die "Failed to fork: $OS_ERROR"; } } # Handle SIGCHILD and restart any child processes that have exited $SIG{CHLD} = sub { while ((my $pid = waitpid(-1, WNOHANG())) > 0) { my $exit_code = $CHILD_ERROR >> 8; if ($exit_code == 0) { print "Child process $pid exited successfully\n"; } else { print "Child process $pid exited with code $exit_code, res +tarting\n"; my $new_pid = fork(); if ($new_pid == 0) { # Child process doWork(); exit; } elsif (!defined $new_pid) { die "Failed to fork: $OS_ERROR"; } } } }; # Main process waits for child processes to exit while (1) { sleep(1); } # Function for child processes to do work sub doWork { # Your code here print "Child process $$ doing some work\n"; sleep(10); }

It's not perfect. The program doesn't exit when all children have finished and i would probably have to prompt it to add that functionality. But overall, i'd say it looks like a reasonable base framework.

What do you think? Any other problems i didn't catch?



(*) Any chance we could use whatever OpenAI used to train ChatGPT to train our newbies here on how to format code?