Mocka : Unix

In the former 'System' section I published about running system commands (Unix commands) from within a compiled program. Why invent a new foreign module for having the program sleep for an amount of time, whereas there is a bugtree program for it built into each and every Linux?

Enter the Unix module:

DEFINITION MODULE Unix;

PROCEDURE Command (VAR  command : ARRAY OF CHAR) : BOOLEAN;

(*	Execute a Unix command (as it is normally ran from the command line)	*)

END Unix.
   
and the associated implementation module:
IMPLEMENTATION MODULE Unix;

IMPORT	SysLib, SYSTEM;

PROCEDURE Command (VAR  command : ARRAY OF CHAR) : BOOLEAN;

BEGIN
   IF  SysLib.system (SYSTEM.ADR (command) ) = 0  THEN
     RETURN TRUE
   ELSE
     RETURN FALSE
   END
END Command;

END Unix.
   
Is it worth making the module for one single function? Yes, it is. Now there's only one funtion in it but Unix has so many commands that sooner or later additional Unix commands may come in handy.

Trying to sleep

Let's see if we can get the program to sleep for 20 seconds.

MODULE slp;

IMPORT InOut, Unix;

BEGIN
  InOut.WriteString ("Going to sleep now for 20 seconds...");
  InOut.WriteLn;
  IF  Unix.Command ("sleep 20") = TRUE  THEN
    InOut.WriteString ("Waking up now....")
  ELSE
    InOut.WriteString ("Sumsing went rong")
  END;
  InOut.WriteLn
END slp.
   
I checked it with my darkroom exposure timer and the 20 seconds were spot on! It may come in handy to make a Unix.sleep command that accepts numerical values instead of the text values of this version.

Where does the output end up?

Now, suppose we issue an 'ls' command, then where does the output of the ls go to? Can we get it in the running program, somehow? Let's just try and see:

MODULE slp;

IMPORT	InOut, Unix;

VAR	ch	: CHAR;

BEGIN
  InOut.WriteString ("Testing ls and see where the output ends up");
  InOut.WriteLn;
  IF  Unix.Command ("ls") = TRUE  THEN
    InOut.WriteString ("ls done")
  ELSE
    InOut.WriteString ("Sumsing went rong")
  END;
  LOOP
    InOut.Read (ch); 
    InOut.Write (ch)
  END;
  InOut.WriteLn
END slp.
   
Resulting in
jan@Beryllium:~/modula/cgi$ slp
Testing ls and see where the output ends up
CGI.def   Unix.h    about.mod   aboutpost      counterCGI.mod  log      oud          rooster2      shopper.mod
CGI.mod   Unix.mod  about2      aboutpost.mod  form1.html      log.mod  rooster      rooster2.mod  slp
Unix.def  about     about2.mod  access.mod     ll              m2bin    rooster.mod  shopper       slp.mod
^C
jan@Beryllium:~/modula/cgi$
   
It ends up in the input stream! Now that is handy. If only I can find a way to know when the input streamis empty. EOF in some kind of form must be around.

Page created 24 March 2013 and