How to run code after ruby Kernel.exec

2020-05-01 06:50发布

I have the following ruby shell.

#!/usr/bin/env ruby

$stdin.each_line do |line|
  pid = fork{
    exec line
    puts "after exec -> #{Process.pid}"
  }
  Process.wait pid
end

The puts method after exec is never executed. Based on ri Kernel.exec, it seems that exec replaces the current process by running the given external. So, it's supposed to replace the new forked processes with the external processes. How am I supposed to run anything after exec command?

标签: ruby shell unix
1条回答
ら.Afraid
2楼-- · 2020-05-01 07:00

You cannot.

Per the documentation for Kernel#exec, "[it] replaces the current process by running the given external command". That means that you are no longer running your code but instead the code you specified by the command.

If you want to "wrap" a system call then you should use Kernel#system (or the backtick operator) to execute the command in a subshell.

查看更多
登录 后发表回答