10

I'm trying to nohup a command and run it as a different user, but every time I do this two processes are spawned.

For example:

$ nohup su -s /bin/bash nobody -c "my_command" > outfile.txt &

This definitely runs my_command as nobody, but there's an extra process that I don't want to shown up:

$ ps -Af
.
.
.
root ... su -s /bin/bash nobody my_command
nobody ... my_command

And if I kill the root process, the nobody process still lives... but is there a way to not run the root process at all? Since getting the id of my_command and killing it is a bit more complicated.

Kappa
  • 1,015
  • 1
  • 16
  • 31
Apothem
  • 405
  • 1
  • 5
  • 12

5 Answers5

14

This could be achieved as:

su nobody -c "nohup my_command >/dev/null 2>&1 &"

and to write the pid of 'my_command' in a pidFile:

pidFile=/var/run/myAppName.pid
touch $pidFile
chown nobody:nobody $pidFile
su nobody -c "nohup my_command >/dev/null 2>&1 & echo \$! > '$pidFile'"
javdev
  • 794
  • 2
  • 10
  • 23
4
nohup runuser nobody -c "my_command my_command_args....." < /dev/null >> /tmp/mylogfile 2>&1 &
Igor
  • 33,276
  • 14
  • 79
  • 112
2

If the user with nologin shell, run as follows:

su - nobody -s /bin/sh -c "nohup your_command parameter  >/dev/null 2>&1 &"

Or:

runuser - nobody -s /bin/sh -c "nohup your_command parameter  >/dev/null 2>&1 &"

Or:

sudo su - nobody -s /bin/sh -c "nohup your_command parameter  >/dev/null 2>&1 &"

sudo runuser -u nobody -s /bin/sh -c "nohup your_command parameter  >/dev/null 2>&1 &"
Wangwang
  • 157
  • 2
1

You might do best to create a small script in e.g. /usr/local/bin/start_my_command like this:

#!/bin/bash
nohup my_command > outfile.txt &

Use chown and chmod to set it to be executable and owned by nobody, then just run su nobody -c /usr/local/bin/start_my_command.

twalberg
  • 59,951
  • 11
  • 89
  • 84
0

A note on running this on a session, is that if you run in background, there is a job associated with the session, and background jobs may be killed (the su -c gets around this).

To disassociate the process from the shell (so you can exit the shell but keep the process running), use disown.

Brett
  • 5,690
  • 6
  • 36
  • 63