Magical ‘If..then..else’ conditional statement

Bookmark this on Digg
Bookmark this on Delicious
Share on Facebook
Post to Google Buzz
Bookmark this on Yahoo Bookmark
Share on FriendFeed
[`tweetmeme` not found]

I believe whole programming world stands on couple of pillars and ‘if..then..else’ (ITE) statement is one of those. Everyone programmer and non-programmer understands ITE conditional statement for sure.

 A typical if..then..else.. statement in Ruby:

 if 1 == 2
   puts "inside if statement"
 else
   puts "inside else statement"
 end
1.9.3p385  > inside else statement
Another example in ruby:
#/bin/ruby
near = "father"
if near == "father"
  puts "I'm studying"
elsif near == "mother"
 puts "I'm playing"
else
 puts "I'm sleeping"
end

1.9.3p385  > I'm studying

Essence is either of two given block is executed i.e. either if block or else block is executed by the code in any language.

Can there be a case/situation when both of these blocks if & else are executed?

…. This is really an unusual question but seriously can this be achieved. Can we challenge the very existence of conditional flow? Are the basics we have learned aren’t true anymore?

Answer lies in situation and yes this can be achieved. Unix fork(2) is the answer and can help if..then..else to behave in this manner.

example magicalif.rb

if f1 = fork
  puts "inside fork"
elsif f2 = fork
  puts "inside second fork"
else
  puts "outside fork"
end

─$ ruby magicalif.rb

inside fork
inside second fork
outside fork

So what has just happened? Condition checks for fork(2), kernel command to create a subprocess of the parent process.  So fork, creates a subprocess called child process similar to parent process (having copy of parent process, file descriptors and sockets etc) and returns a pid (child process) to parent process and nil to child process. Hence, IF block was executed by parent process as it returned pid to parent process and ELSE statement is executed by CHILD process as fork returned nil to child process.

Let’s have a closer look which block is executed by which process (parent or child)

supermagicalif.rb

puts "Master Process: #{Process.pid}"
if f1 = fork
  puts "inside fork"
  puts "Fork PID: #{f1}"
  puts "Process pid: #{Process.pid}"
elsif f2 = fork
  puts "inside second fork"
  puts "Fork PID: #{f2}"
  puts "Process pid: #{Process.pid}"
else
  puts "outside fork"
  puts "Process pid: #{Process.pid}"
end

─$ ruby supermagicalif.rb
Master Process: 21267
inside fork
Fork PID: 21268
Process pid: 21267
inside second fork
Fork PID: 21269
Process pid: 21268
outside fork
Process pid: 21269

This clearly shows IF block is executed by PARENT process, ELSIF block executed by first CHILD process and ELSE block executed by SECOND CHILD process.

Will have a more closer look in fork(2) in next blog where will see it’s usage and how can it be used in our programming. For now, yes it’s possible and now you know MAGICAL IF..THEN..ELSE statement 🙂