#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    1
    Rep Power
    0

    Problem with fork


    I am exploring fork to have multiple client session.

    With the below code, I am trying to understand the fork logic.

    But each and every time I execute the program, I get different results.

    Moreover in the output, I don't see 1000 "this is the message from server" in the obtained output, each and every time the count varies, why it is,


    #!/usr/bin/perl -w
    use strict;

    #my @servers = qw(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20);

    foreach my $server (1..1000) {
    print "this is the message from server\n";
    my $pid;
    next if $pid = fork; # Parent goes to next server.
    die "fork failed: $!" unless defined $pid;
    my $i;
    for ($i=1;$i<=4;$i++)
    {
    print "I am in child\n";
    }
    exit; # Ends the child process.
    }
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,392
    Rep Power
    1871
    > But each and every time I execute the program, I get different results.
    If by different, you mean a different order of lines, then that is to be expected.
    Once you've forked a process, each has an independent life.

    Code:
    #!/usr/bin/perl -w
    use strict;
    
    #my @servers = qw(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20);
    
    foreach my $server (1..5) {
        print "this is the message from server\n";
        my $pid;
        next if $pid = fork; # Parent goes to next server.
        die "fork failed: $!" unless defined $pid;
        my $i;
        for ($i=1;$i<=4;$i++)
        {
            print "I am in child $$\n";
        }
        exit; # Ends the child process.
    }
    
    
    $ perl foo.pl
    this is the message from server
    this is the message from server
    this is the message from server
    I am in child 2724
    I am in child 2724
    I am in child 2724
    I am in child 2724
    this is the message from server
    I am in child 2725
    I am in child 2725
    I am in child 2725
    I am in child 2725
    this is the message from server
    I am in child 2726
    I am in child 2726
    I am in child 2726
    I am in child 2726
    I am in child 2727
    I am in child 2727
    I am in child 2727
    I am in child 2727
    I am in child 2728
    I am in child 2728
    I am in child 2728
    I am in child 2728
    There are 5 server messages, and 5 different children, each of which runs 4 times.

    Now, if you try and fork 1000 processes in quick succession, then it might just fail for other reasons.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo