2

I'm programmatically spawning processes in bash. I need to be able to pass in arbitrary environment variables and commands. To achieve this I'm running /usr/bin/env and then calling bash -c. Sometimes the process I started doesn't stop and I want to kill it, however when I kill the PID that comes back from my command, it only kills the bash command and not the the child process that bash ran.

I've seen Forward SIGTERM to child in Bash so I think the problem can be fixed with bash exec however I can't invoke the correct command.

For example here is a ruby script that never exits:

STDOUT.sync = true

puts "booted"

while true
  puts "running"
  sleep 1
end

When I run it via $ exec ruby spec/fixtures/never_exits.rb, the program behaves as I want. When I kill my bash session the program is terminated.

However when I try to run this with env like $ /usr/bin/env bash -c exec ruby spec/fixtures/never_exits.rb, the command exits immediately and there's no output. It doesn't look like the script is being invoked.

Is it possible to use exec in combination with specifying environment variables?

Is there another way to propagate the TERM to a child process that could be invoked in one line?

2

When using bash -c type structures you need to put the whole command inside " characters. e.g

$ bash -c echo hello

$ bash -c "echo hello"
hello

So in your case

env bash -c "exec ruby script.rb"

However, the env in this example doesn't really do much; did you mean env -i to create an initial environment? Also, unless there's some magic happening inside the bash startup scripts, you may not need bash at all.

 env -i RUBYPATH=/some/dir RUBYLIB=/other/dir /path/to/ruby script.rb
  • I left out the args to /usr/bin/env in this example for clarity. In the libary people can specify arbitrary env vars which is a hard requirement even though I didn't need them to demonstrate this failing case. That worked, thanks! – Schneems Jun 13 '16 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.