3

In bash, how can I initiate a job in a stopped state, as if I started it normally and then immediately pressed Ctrl-Z?

Or as if I had sent SIGSTOP to the process immediately, but without giving the process a chance to execute before it receives the SIGSTOP.

nibot
  • 1,987
  • 4
  • 14
  • 18
  • Duplicate of http://serverfault.com/questions/293632/how-do-i-start-a-process-in-suspended-state-under-linux ? – Foon Oct 07 '12 at 11:39
  • Yes, it's an exact duplicate. Unfortunately the other question also has not been answered to my satisfaction. – nibot Oct 07 '12 at 11:47

2 Answers2

6

You can start a new subshell, immediatelly stop it, and then (i.e. after makint it run again) run your command. I used the $BASHPID variable to get the PID of the subshell, as $$ still returns the PID of the parent:

( kill -SIGSTOP $BASHPID; exec my_command )

Using exec here will cause the my_command process to use the same PID as the subshell.

choroba
  • 18,638
  • 4
  • 48
  • 52
  • 1
    Change it to `( kill -SIGSTOP $BASHPID; exec my_command )` and I think we have a winner! – nibot Oct 07 '12 at 12:10
4

I know this question is quite old, but just in case someone is looking for this functionality, like I was:

I recently added this to my LD_PRELOAD module collection (https://github.com/zardus/preeny). Using preeny, you can have a process suspend itself on startup:

# https://github.com/zardus/preeny
# cd preeny
# make
# LD_PRELOAD=x86_64-linux-gnu/startstop.so /bin/echo TEST
[1]+  Stopped    LD_PRELOAD=x86_64-linux-gnu/startstop.so /bin/echo TEST
# fg
TEST

Preeny suspends the process during library startup, before main() is called.

Zardus
  • 141
  • 1
  • 1
    Hi Zardus, and welcome to Super User. No worries about answering an old question. This is an interesting approach! – user May 10 '15 at 21:29
  • This approach is nice, because it actually loads the binary. However, I guess other constructor functions can run before preeny. – user877329 Jul 17 '17 at 13:37
  • Yes... I haven't found a way to control the execution order of constructors, unfortunately. – Zardus Jul 18 '17 at 18:04