3

Let's say I send two jobs to the background.

$ sleep 77 &
$ sleep 99 &

Then I check my jobs

$ jobs
> [1]  - running    sleep 77
> [2]  + running    sleep 99

Can I control what job number gets assigned to these jobs? I'm not sure if I'm using the right terminology here, I'm talking about the numbers denoted as [1] and [2] in the example before.

The use case is the following: I need a job that renews my credentials every now and then, but most of the time it is asleep. I wrote a function that is automatically sent to the background if called. I do this deliberately since I want to have control over this process, i.e. I explicitly want to have it as a job.

when I call the function and there are no other jobs, it gets the job number [2]. (I assume [1] would be the subprocess calling the function.) This is confusing, since when I later send job1 to the background, it gets the job number [1], but job2 gets the job number [3]. I would prefer if I could assign a large number to my sleeping function by hand, e.g. something like [99]. Is this possible? Either in bash or zsh?

  • do you need to bring the job to the foreground to control it, or do you just need to stop and restart it, or to send it some messages or such? – ilkkachu Jan 1 '18 at 20:38
  • @ilkkachu Just stop and restart. Mostly I do not interact with it at all. – pfnuesel Jan 1 '18 at 20:40
0

No, you can't specify the job number assigned to a backgrounded process.

You can, however, get the PID of the most recently backgrounded process with $! - which is far more useful.

e.g.

$ sleep 77 &
[5] 21959
$ job1=$!

$ sleep 99 &
[6] 21960
$ job2=$!

$ echo job1=$job1 job2=$job2
job1=21959 job2=21960

and, later (but before the first job finishes):

$ kill "$job1"
[1]-  Terminated              sleep 77

see man bash and search for JOB CONTROL for more details about backgrounds jobs.

(note: job control is pretty much the same in all bourne-style shells - but bash has, by far, the best man page documentation about it)

  • PS: by "pretty much the same", I mean I can't recall any differences between the various alternative shells, but don't have time to thoroughly research it right now. I'm about 99.99% confident that there aren't even any minor differences, let alone significant ones, but there's always the chance I've forgotten something. – cas Jan 2 '18 at 5:31

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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