Skip to content

Commit

Permalink
Merge pull request #2205 from herwinw/kernel_backtick
Browse files Browse the repository at this point in the history
Move shell_backtick function inline in KernelModule::backtick
  • Loading branch information
herwinw committed Jul 10, 2024
2 parents 32ba343 + 1bc7e18 commit 7ebed36
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 29 deletions.
2 changes: 0 additions & 2 deletions include/natalie.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,6 @@ std::pair<Value, Value> coerce(Env *, Value, Value, CoerceInvalidReturnValueMode
Block *to_block(Env *, Value);
inline Block *to_block(Env *, Block *block) { return block; }

Value shell_backticks(Env *, Value);

FILE *popen2(const char *, const char *, pid_t &);
int pclose2(FILE *, pid_t);

Expand Down
22 changes: 21 additions & 1 deletion src/kernel_module.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,27 @@ Value KernelModule::at_exit(Env *env, Block *block) {
}

Value KernelModule::backtick(Env *env, Value command) {
return shell_backticks(env, command->to_str(env));
constexpr size_t NAT_SHELL_READ_BYTES = 1024;
pid_t pid;
auto process = popen2(command->to_str(env)->c_str(), "r", pid);
if (!process)
env->raise_errno();
char buf[NAT_SHELL_READ_BYTES];
auto result = fgets(buf, NAT_SHELL_READ_BYTES, process);
StringObject *out;
if (result) {
out = new StringObject { buf };
while (1) {
result = fgets(buf, NAT_SHELL_READ_BYTES, process);
if (!result) break;
out->append(buf);
}
} else {
out = new StringObject {};
}
int status = pclose2(process, pid);
set_status_object(env, pid, status);
return out;
}

Value KernelModule::binding(Env *env) {
Expand Down
26 changes: 0 additions & 26 deletions src/natalie.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -740,32 +740,6 @@ Block *to_block(Env *env, Value proc_or_nil) {
return proc_or_nil->to_proc(env)->block();
}

#define NAT_SHELL_READ_BYTES 1024

Value shell_backticks(Env *env, Value command) {
command->assert_type(env, Object::Type::String, "String");
pid_t pid;
auto process = popen2(command->as_string()->c_str(), "r", pid);
if (!process)
env->raise_errno();
char buf[NAT_SHELL_READ_BYTES];
auto result = fgets(buf, NAT_SHELL_READ_BYTES, process);
StringObject *out;
if (result) {
out = new StringObject { buf };
while (1) {
result = fgets(buf, NAT_SHELL_READ_BYTES, process);
if (!result) break;
out->append(buf);
}
} else {
out = new StringObject {};
}
int status = pclose2(process, pid);
set_status_object(env, pid, status);
return out;
}

// https://stackoverflow.com/a/26852210/197498
FILE *popen2(const char *command, const char *type, pid_t &pid) {
pid_t child_pid;
Expand Down

0 comments on commit 7ebed36

Please sign in to comment.