I am trying to create a program to communicate with tdlib-json-cli in Lua using Redbean.dev.
So far, I have written this code:
function OnServerStart()
print("Server started")
local reader, writer = assert(unix.pipe())
if assert(unix.fork()) == 0 then
print("Run child fork")
unix.close(1)
-- unix.dup(reader, 0)
unix.dup(writer)
unix.close(writer)
unix.close(reader)
print("Run tdlib_json_cli-linux-gcc")
assert(unix.sigaction(unix.SIGTERM, unix.exit))
unix.execve("/root/tdlib_json_cli-linux-gcc", {"/root/tdlib_json_cli-linux-gcc"}) -- path to tdlib_json_cli here
unix.exit(127)
else
print("Run parent fork")
if assert(unix.fork()) == 0 then -- do not block the main proccess
assert(unix.sigaction(unix.SIGTERM, unix.exit))
while true do
local data, err = unix.read(reader)
if data then
if data ~= '' then
print(string.format("Got data: %q", data))
--unix.write(writer, "exitn") --> How to write to pipe here?
--break
else
break
end
elseif err:errno() ~= EINTR then
Log(kLogWarn, tostring(err))
break
end
end
assert(unix.close(writer))
assert(unix.close(reader))
end
end
For reference, the C++ code for tdlib-json-cli is this:
(there is a precompiled release in the repository)
#include <iostream>
#include <string>
#include <thread>
#include "td/td/telegram/td_json_client.h"
#include "td/td/telegram/Log.h"
void* client;
int should_stop = 0;
void proc_thread_input();
void proc_thread_output();
void trigger_cli_event(std::string);
void set_verbosity(char const *);
int main(int argc, char const *argv[])
{
set_verbosity(argv[1]);
client = td_json_client_create();
trigger_cli_event("client_created");
std::thread thread_input(proc_thread_input);
std::thread thread_output(proc_thread_output);
thread_input.join();
should_stop = 1;
thread_output.join();
trigger_cli_event("exited");
return 0;
}
void proc_thread_input() {
std::string input;
while (std::cin) {
getline(std::cin, input);
if (input == "exit") {
break;
}
if (input.empty()) {
continue;
}
if (input.rfind("verbose ", 0) == 0) {
// verbose<space>
// 01234567
set_verbosity(input.substr(7).c_str());
continue;
}
td_json_client_send(client, input.c_str());
}
}
void proc_thread_output() {
const char* output;
while (should_stop == 0) {
output = td_json_client_receive(client, 1);
if (output != NULL) {
std::cout << output << std::endl;
}
}
}
void trigger_cli_event(std::string event_name) {
std::cout << "{"@cli":{"event":"" << event_name << ""}}" << std::endl;
}
void set_verbosity(char const *argv) {
if (argv == NULL) return;
auto level = atoi(argv);
td::Log::set_verbosity_level(level);
trigger_cli_event("verbosity_set");
}
I cannot read/write to the pipe.
What might I be doing wrong in my Lua code?
I want my code to send “verbose 1” or “exit” or another JSON data to tdlib-json-cli and have it respond to unix.read.
New contributor
secjoa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.