Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
1.7 KiB

  1. #!/usr/local/ActivePerl-5.6/bin/perl -w
  2. #
  3. # forker.pl
  4. #
  5. # This script is a simple demonstration of how to use fork()
  6. #
  7. # Author: David Sparks <[email protected]>
  8. use strict;
  9. use warnings;
  10. use constant CLIENTS => 32;
  11. use constant DEBUG => 1;
  12. $|=1; #buffering a bad idea when fork()ing
  13. my @kids=();
  14. my $pid=$$;
  15. my $parentpid=0;
  16. #script starts here
  17. SharedInit();
  18. Forker(CLIENTS);
  19. if ($parentpid) {
  20. Work();
  21. }
  22. else { #the original parent only does cleanup duty
  23. Reaper();
  24. }
  25. warn "$$ exiting\n" if DEBUG;
  26. if ($parentpid) {
  27. #kids exit here
  28. exit(0);
  29. }
  30. else {
  31. #parent exits here
  32. exit(0);
  33. }
  34. die; #wont happen
  35. sub Forker {
  36. my $clients=shift;
  37. my $i=0;
  38. while ($i++ < $clients) {
  39. my $newpid = fork();
  40. if (! defined $newpid) { #hosed
  41. die "fork() error: $!\n";
  42. }
  43. elsif ($newpid == 0) { #child
  44. $parentpid = $pid;
  45. $pid = $$;
  46. @kids = (); #don't inhert the kids
  47. warn "$$ child of $parentpid\n" if DEBUG;
  48. last;
  49. }
  50. else { #parent (defined $newpid)
  51. warn "$$ spawned $newpid\n" if DEBUG;
  52. push(@kids, $newpid);
  53. }
  54. }
  55. }
  56. sub SharedInit {
  57. warn "Entering SharedInit()\n" if DEBUG;
  58. }
  59. sub Work {
  60. warn "$$ Entering Work()\n" if DEBUG;
  61. }
  62. sub Reaper {
  63. while (my $kid = shift(@kids)) {
  64. warn "$$ to reap $kid\n" if DEBUG;
  65. my $reaped = waitpid($kid,0);
  66. unless ($reaped == $kid) {
  67. warn "waitpid $reaped: $?\n" if DEBUG;
  68. }
  69. }
  70. }
  71. __END__
  72. use POSIX ":sys_wait_h";
  73. do {
  74. $kid = waitpid(-1,&WNOHANG);
  75. } until $kid == -1;