How to run code after ruby Kernel.exec

2020-05-01 06:33发布

问题:

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?

回答1:

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.



标签: ruby shell unix