1#
2#  old-fashioned 'shl' like program
3#  by A. Ito
4#
5#  commands:
6#     c        creates new shell
7#     C-z      suspends shell
8#     p        lists all shell
9#     0,1,...  choose shell
10#     q        quit
11
12require 'pty'
13
14$shells = []
15$n_shells = 0
16
17$r_pty = nil
18$w_pty = nil
19
20def writer
21  system "stty -echo raw"
22  begin
23    while true
24      c = STDIN.getc
25      if c == 26 then # C-z
26        $reader.raise(nil)
27        return 'Suspend'
28      end
29      $w_pty.print c.chr
30      $w_pty.flush
31    end
32  rescue
33    $reader.raise(nil)
34    return 'Exit'
35  ensure
36    system "stty echo -raw"
37  end
38end
39
40$reader = Thread.new {
41  while true
42    begin
43      next if $r_pty.nil?
44      c = $r_pty.getc
45      if c.nil? then
46        Thread.stop
47      end
48      print c.chr
49      STDOUT.flush
50    rescue
51      Thread.stop
52    end
53  end
54}
55
56# $reader.raise(nil)
57
58
59while true
60  print ">> "
61  STDOUT.flush
62  case gets
63  when /^c/i
64    $shells[$n_shells] = PTY.spawn("/bin/csh")
65    $r_pty,$w_pty = $shells[$n_shells]
66    $n_shells += 1
67    $reader.run
68    if writer == 'Exit'
69      $n_shells -= 1
70      $shells[$n_shells] = nil
71    end
72  when /^p/i
73    for i in 0..$n_shells
74      unless $shells[i].nil?
75        print i,"\n"
76      end
77    end
78  when /^([0-9]+)/
79    n = $1.to_i
80    if $shells[n].nil?
81      print "\##{i} doesn't exist\n"
82    else
83      $r_pty,$w_pty = $shells[n]
84      $reader.run
85      if writer == 'Exit' then
86        $shells[n] = nil
87      end
88    end
89  when /^q/i
90    exit
91  end
92end
93