How to continuously show os command output in erlang? - operating-system

I need continuously show stdout/stderr from os command in erlang.
In ruby I can implement it with following code:
s1, s2 , s3, t = Open3.popen3('for %a in (1 2 3 4 5 6 7 8 9) do (echo message & sleep 2 ) 2>&1 ')
s2.each do |l|
puts l
end
it will show 'message\n message\n' in 'real time' - does not wait end of process.
I've tried os:cmd(..)
and
1> P5 = erlang:open_port({spawn, "ruby rtest.rb"}, [stderr_to_stdout, in, exit_s
tatus, binary,stream, {line, 255}]).
#Port<0.505>
2> receive {P5, Data} -> io:format("Data ~p~n",[Data]) end.
Data {data,{eol,<<>>}}
ok
but both of them wait end of process.
Are the any optional for continuously stdout reading in Erlang?
EDIT:
In other words I look for a popen (c/c++; proc_open(php) and etc) function in erlang
EDIT2
Code, that works on linux (tested on centos6.2). Thanks for vinod:
-module(test).
-export([run/0]).
run() ->
P5 = erlang:open_port({spawn, "sh test.sh"},
[stderr_to_stdout, in, exit_status,stream, {line, 255}]),
loop(P5).
loop(P) ->
receive{P, Data} ->
io:format("Data ~p~n",[Data]),
loop(P)
end.
Output:
10> c(test).
{ok,test}
11> test:run().
Data {data,{eol,"1"}}
Data {data,{eol,"2"}}
Data {data,{eol,"3"}}
Data {data,{eol,"4"}}
Data {data,{eol,"5"}}
Data {data,{eol,"6"}}
Data {data,{eol,"7"}}
Data {data,{eol,"8"}}
Data {data,{eol,"9"}}
Data {data,{eol,"10"}}
Data {exit_status,0}

If I understand correctly, you want to continue to execute your program in concurrent with the os command. In Erlang you can just spawn a process which does that and you can continue. For example
1> spawn(fun() ->
P5 = erlang:open_port({spawn, "ruby rtest.rb"},
[stderr_to_stdout, in, exit_status,
binary,stream, {line, 255}]),
receive {P5, Data} ->
io:format("Data ~p~n",[Data])
end
end).
<0.32.0>
2> 5+5.
10
3>
Better to write in a module so that you can understand it better.

Related

How to exit a REPL from the command line

I'm currently learning Lua and also learning how to work with CMD.
I know how to change a directory path and run my codes and files from that path
but what I don't know and I'm here to ask for is how to get out of a programming language REPL when you start it in CMD
For example to jump into the Lua REPL you should type:
lua53 (--like python3 for the Python language)
then you changed the CMD environment to a Lua compiler and can't access CMD commands such as
dir, cd, cls etc. and everytime when I need to access these commands I have to close the CMD window and open a new one.
Now can you guys tell me am I able to access CMD commands while in the Lua REPL? Or do I have to exit Lua first, and is there any command to exit a REPL?
I'd recommend EOF (Ctrl + D on Unix) rather than SIGKILL (Ctrl + C) because some REPLs (node and python) choose to ignore the latter (perhaps because it's often used for copying text?); python will just print KeyboardInterrupt whereas node will only exit if you press Ctrl + C twice (it will send a message telling you this the first time).
EOF (Ctrl + D) on the other hand immediately exists all REPLs I have used so far.
The Lua REPL stops immediately when it receives either EOF or SIGKILL, so you can use both here.
Edit: As Sowban points out, EOF apparently is entered as Ctrl + Z then Enter in powershell.
You could type ctrl c to exit the process that's running generally.
I suggest to write a REPL by yourself.
But be warned :-)
The main loop with a prompt and the interpreting and executing function/method is mostly the easiest part.
99.99999% is the errorhandling thing.
One of my earliest interpreter language is (A)REXX.
A REPL without any errorhandling is done with...
/* REXX have to start with a comment */
do forever
parse pull input
interpret input
end
Now Lua sandboxed to an _ENV with io and os library and a little bit of errorhandling...
#!/usr/bin/env -S readline-editor /usr/local/bin/lua
-- ^--SHEBANG for Linux --------------------------------------------------------------------------------------
-- interpreter.lua
-- Sandboxed to io and os
-- Lua 5.4 >>-because-> goto label <const> load()
--------------------------------------------------------------------------------------------------------------
local Lua = function(...)
-- Info about OS
io.write(("%s\n"):format(io.popen('uname -a'):read())):flush()
-- Global Setting
debug.setmetatable((1), {__index = math}) -- Add math library to number as methods (like string for strings)
os.setlocale('de_DE.UTF8')
os.setlocale('en_US.UTF8', 'time')
io.write(os.date("[%c]\n" .. ("%s\n"):format(os.setlocale():gsub("%;", "\n")))):flush()
-- io.write(("%s\n"):format(_VERSION)):flush()
-- Label for goto
::lua::
-- Local Setting
local args <const> = args or {...}
local Lua = Lua or true
local cmd = cmd or ""
--------------------------------------------------------------------------------------------------------------
local env <const> = env or setmetatable({os = os, io = io}, -- The _ENV for load()
{__call = function(self, ...)
local self, t = ({...})[1] or self, "" -- First argument becomes self if one
if ({...})[1] == "help" then self = getmetatable(({...})[2]).__index end -- Showing metamethod __index (table)
for k, v in pairs(self) do
t = t .. ("%s => %s\n"):format(k, v)
end
return t
end,
__index = {cg = collectgarbage,
gt = getmetatable,
pairs = pairs,
tn = tonumber,
ts = tostring,
_V = ("%s \27[1;" .. (31):random(36) .. "m(sandboxed)\27[0m"):format(_VERSION)},
__tostring = function(self) return self._V end}) -- end env
--------------------------------------------------------------------------------------------------------------
local prompt = prompt or setmetatable({}, {__tostring = function() return getmetatable(env).__index._V .. "> " end})
local name <const> = name or _VERSION
local result = result or true
--------------------------------------------------------------------------------------------------------------
while Lua do
io.write(tostring(prompt))
cmd = io.read() or 'quit'
if cmd == "quit" then Lua, result = true, true break end
Lua, result = pcall(load("return " .. cmd or false, name, "t", env))
if Lua and result then
io.write(("%s"):format(tostring(result)))
else
goto exception
end
end
--------------------------------------------------------------------------------------------------------------
-- Errorhandler
::exception::
io.write(("%s\n"):format("Exception"))
if not Lua or not result then
io.output(io.stderr)
io.write(("[%s][%s][%s]\n\27[1;31m>>-Exception->\27[0m %s\n"):format(os.date(), _VERSION, cmd, result)):flush()
io.output(io.stdout)
collectgarbage()
goto lua
end
goto lua
end
--------------------------------------------------------------------------------------------------------------
-- EXAMPLE ---------------------------------------------------------------------------------------------------
-- Lua = require("interpreter")
Lua() -- UNCOMMENT-> For direct execution like: /bin/lua interpreter.lua
return Lua -- UNCOMMENT-> For: Lua = require("interpreter")
Ctrl&C quits hardly
Ctrl&D is only an exception
...and os.exit(0) do an clean exit with returncode 0.
Impression

OCaml flush strange behaviour (exiting all threads)

I try to implement a CLI with 2 commands:
run that spawns an unix socket at /my/path/file.sock and produces output
watch that connects to the socket and forward the output to its own output
When I kill the watch command, I can't understand why the run command is also killed. They don't raise any exception nor sys signal. I noticed that the problems comes from the flush function. Once called, it acts like a exit 0. How come?
Here the sources: https://github.com/soywod/comodoro
The server has to listen for client disconnection and remove the connection from the conn list.
Something like this might work:
let client_thread conn =
let in_ch = in_channel_of_descr conn in
while true do
try input_line in_ch |> ignore
with End_of_file ->
(* Remove conn from !conn and close the conn *)
done
in
let add_conn () =
(* ... *)
Thread.create client_thread conn |> ignore;
(* ... *)
in

I2C returning Busy or Error on memory reading

I started the following code to handle a Bosch BME280 sensor with a Nucleo-F446ZE and a Nucleo-F411RE boards.
with STM32.Device; use STM32.Device;
with STM32.GPIO; use STM32.GPIO;
with STM32; use STM32;
with STM32.I2C;
with HAL.I2C; use HAL.I2C;
use HAL;
procedure Simple_I2C_Demo is
-- I2C Bus selected
Selected_I2C_Port : constant access STM32.I2C.I2C_Port := I2C_1'Access;
Selected_I2C_Port_AF : constant GPIO_Alternate_Function := GPIO_AF_I2C1_4;
Selected_I2C_Clock_Pin : GPIO_Point renames PB8;
Selected_I2C_Data_Pin : GPIO_Point renames PB9;
Port : constant HAL.I2C.Any_I2C_Port := Selected_I2C_Port;
-- Shift one because of 7-bit addressing
I2C_Address : constant HAL.I2C.I2C_Address := 16#76# * 2;
procedure SetupHardware is
GPIO_Conf_AF : GPIO_Port_Configuration (Mode_AF);
Selected_Clock_Speed : constant := 10_000;
begin
Enable_Clock (Selected_I2C_Clock_Pin);
Enable_Clock (Selected_I2C_Data_Pin);
Enable_Clock (Selected_I2C_Port.all);
STM32.Device.Reset (Selected_I2C_Port.all);
Configure_Alternate_Function (Selected_I2C_Clock_Pin, Selected_I2C_Port_AF);
Configure_Alternate_Function (Selected_I2C_Data_Pin, Selected_I2C_Port_AF);
GPIO_Conf_AF.AF_Speed := Speed_100MHz;
GPIO_Conf_AF.AF_Output_Type := Open_Drain;
GPIO_Conf_AF.Resistors := Pull_Up;
Configure_IO (Selected_I2C_Clock_Pin, GPIO_Conf_AF);
Configure_IO (Selected_I2C_Data_Pin, GPIO_Conf_AF);
STM32.I2C.Configure
(Selected_I2C_Port.all,
(Clock_Speed => Selected_Clock_Speed,
Addressing_Mode => STM32.I2C.Addressing_Mode_7bit,
Own_Address => 16#00#, others => <>));
STM32.I2C.Set_State (Selected_I2C_Port.all, Enabled => True);
end SetupHardware;
ID : HAL.I2C.I2C_Data (1 .. 1);
Status : HAL.I2C.I2C_Status;
begin
SetupHardware;
HAL.I2C.Mem_Read (This => Port.all,
Addr => I2C_Address,
Mem_Addr => 16#D0#,
Mem_Addr_Size => HAL.I2C.Memory_Size_8b,
Data => ID,
Status => Status,
Timeout => 15000);
if Status /= Ok then
raise Program_Error with "I2C read error:" & Status'Img;
end if;
end Simple_I2C_Demo;
In this simple example, I always get an error status at the end of reading. In the context of a more complete code, I always get a Busy status after waiting 15secs.
I really don't see what is going on as my code is largely inspired from the code I found on Github for a I2C sensor.
Maybe I forgot a specific code for I2C init but as I'm not an expert, I prefer to ask to experts :)
Finally found what was wrong. After testing with C using STM HAL and investigating the Ada configuration code, I found that a line was missing:
GPIO_Conf_AF.AF_Speed := Speed_100MHz;
GPIO_Conf_AF.AF_Output_Type := Open_Drain;
GPIO_Conf_AF.Resistors := Pull_Up;
-- Missing configuration part of the record
GPIO_Conf_AF.AF := Selected_I2C_Port_AF;
-- That should be present even though there was a call to configure
-- each pin few lines above
Configure_IO (Selected_I2C_Clock_Pin, GPIO_Conf_AF);
Configure_IO (Selected_I2C_Data_Pin, GPIO_Conf_AF);
Using Configure_IO after Configure_Alternate_Function crushes the configuration and, as there was a part of the record which was left uninitialized, the GPIO were incorrectly configured.
To be more precise, after looking at the code inside the GPIO handling, Configure_IO calls Configure_Alternate_Function using the AF part of the GPIO_Port_Configuration record. In my case, it was resetting it.
With the missing line, the code now runs correctly with Mem_Read and Master_Transmit/Master_Receive.
A big thanks to ralf htp for advising me to dive into the generated C code.
No, between HAL_I2C_Mem_Read and the HAL_I2C_Master_Transmit, wait, HAL_I2C_Master_Receive procedure is only a nuance cf How do I use the STM32CUBEF4 HAL library to read out the sensor data with i2c? . If you know what size of data you want to receive you can use the HAL_I2C_Master_Transmit, wait, HAL_I2C_Master_Receive procedure.
A C++ HAL I2C example is in https://letanphuc.net/2017/05/stm32f0-i2c-tutorial-7/
//Trigger Temperature measurement
buffer[0]=0x00;
HAL_I2C_Master_Transmit(&hi2c1,0x40<<1,buffer,1,100);
HAL_Delay(20);
HAL_I2C_Master_Receive(&hi2c1,0x40<<1,buffer,2,100);
//buffer[0] : MSB data
//buffer[1] : LSB data
rawT = buffer[0]<<8 | buffer[1]; //combine 2 8-bit into 1 16bit
Temperature = ((float)rawT/65536)*165.0 -40.0;
//Trigger Humidity measurement buffer[0]=0x01;
HAL_I2C_Master_Transmit(&hi2c1,0x40<<1,buffer,1,100);
HAL_Delay(20);
HAL_I2C_Master_Receive(&hi2c1,0x40<<1,buffer,2,100);
//buffer[0] : MSB data
//buffer[1] : LSB data
rawH = buffer[0]<<8 | buffer[1]; //combine 2 8-bit into 1 16bit
Humidity = ((float)rawH/65536)*100.0; HAL_Delay(100); }
Note that it uses HAL_I2C_Master_Transmit, waits 20 ms until the slave puts the data on the bus and then receives it with HAL_I2C_Master_Receive. This code is working, i tested it myself.
Possibly the problem is that the BME280 supports single byte reads and multi-byte reads (until it sends a NOACK and stop). HAL_I2C_Mem_Read waits for the ACK or stop but for some reasons it does not get it what causes the Busy and then Timeout behavior, cf page 33 of the datasheet http://www.embeddedadventures.com/datasheets/BME280.pdf for the multibyte read. You specified timeout to 15 sec and you get the timeout after 15 secs. So it appears that the BME280 simply does not stop sending or it sends nothing including not a NOACK and Stop condition ...
HAL_I2C_Mem_Read sometimes causes problems, this depends on the slave https://community.arm.com/developer/ip-products/system/f/embedded-forum/7989/trouble-getting-values-with-i2c-using-hal_library
By the way with the
HAL.I2C.Mem_Read (This => Port.all,
Addr => I2C_Address,
Mem_Addr => 16#D0#,
Mem_Addr_Size => HAL.I2C.Memory_Size_8b,
Data => ID,
Status => Status,
Timeout => 15000);
you try to read 1 byte the chip identification number from register D0 cf http://www.embeddedadventures.com/datasheets/BME280.pdf page 26

LWT simple interaction with a subprocess

Here is a simple program that uses the Unix module to interact with a subprocess. I just launch a cat shell command, send it a string and read it back:
#load "unix.cma";; (* Needed if you are in the toplevel *)
let () =
let sin, sout, serr = Unix.open_process_full "cat" [||] in
output_string sout "test\n";
flush sout;
input_line sin |> print_string;
flush stdout;
Unix.close_process_full (sin, sout, serr) |> ignore;;
Recently I started studying the Lwt library, and I wanted to reproduce the same functionality with it. I though that the following should have exactly the same result:
#use "topfind";; (* *)
#thread;; (* Also only for the toplevel *)
#require "lwt.simple-top";; (* *)
let () =
let open Lwt in
let process = Lwt_process.open_process_full ( "cat" , [||] ) in
Lwt_io.write_line process#stdin "test\n"
>>= ( fun () -> Lwt_io.flush process#stdin )
>>= ( fun () -> Lwt_io.read process#stdout )
>>= ( fun str -> Lwt_io.print str )
>>= ( fun () -> Lwt_io.flush Lwt_io.stdout )
|> Lwt_main.run
But it doesn't work as I expect it to -- apparently it reads and then prints an empty string.
I guess I have some fundamental confusion on how Lwt should work, but I cannot figure it out. Can someone show me how one can communicate with a subprocess using Lwt?
Use Lwt_process.shell to make a proper command, in your case, the proper command is the following:
Lwt_process.shell "cat";;
- : Lwt_process.command = ("", [|"/bin/sh"; "-c"; "cat"|])
Also, I suspect, that after you will run your program in a proper way, you will be wondering, why is your program blocking. This reason is because cat process will not finish until you write an EOF to it's input channel. That's why the Lwt_io.read call will not ever finish. A solution would be to close the stdin channel.

Debugging GNU octave: Using dbnext after dbup

I'm using GNU octave 3.6.4. According to the changelog (v 3.2):
Moving up and down the call stack with
dbup and dbdown now works.
However, when I'm in debug mode and excecute dbup followed by dbnext, the next line in the lower frame will be executed. Why is this so and how can it be avoided?
octave -q
octave:1> myfunc_base(2,3)
stopped in /home/seb/octave/myfunc.m at line 5
5: keyboard
debug> dbstack
stopped in:
--> myfunc at line 5 [/home/seb/octave/myfunc.m]
myfunc_base at line 4 [/home/seb/octave/myfunc_base.m]
debug> dbup
stopped in myfunc_base at line 4 % <-- looks good!
debug> dbnext
stopped in /home/seb/octave/myfunc.m at line 6 % <-- damn this is the old frame!
6: sp = a + temp;
debug>
The two test functions:
myfunc.m
function sp = myfunc (a, b, c)
temp = b+c;
keyboard
sp = a + temp;
end
myfunc_base.m
function sp = myfunc_base (aa, bb)
temp = myfunc(aa, aa, bb);
sp = aa + temp;
end
To step out you have to use dbstep out. This matches the behaviour of matlab and everything else would be very stange. You can not step to the next line on any level of the stack if an exception occurs.