The OP asked, "... how I can know if the process is running background or foreground?"
The foreground and background status of a process are reported by
ps as the state of the process.
man ps lists these process states under the heading of
PROCESS STATE CODE.
ps -ef doesn't report process state, but referring to
man ps we find in the
OUTPUT FORMAT CONTROL section that the
-o argument may be used to specify the output of
ps via one or more keywords. These keywords are listed in the
STANDARD FORMAT SPECIFIERS section, and with extraordinary persistence one will eventually find the
state keywords listed. But note that while all three of these keywords will provide state in the output, only the
stat keyword will give the
multi-character process state! The take-away:
ps favors the diligent user.
As an example, the following
ps command will output the PID, the state, and the command that started the process using the keywords
ps -eo pid,stat,command
To see how this works, consider this example:
In one terminal, run this command:
ping 184.108.40.206 > /dev/null
In another terminal:
ps -eo pid,stat,command | grep ping | grep -v grep
12518 S+ ping 220.127.116.11
Which informs us:
- the PID is
- the process state is
S+ (via keyword
command that spawned the process was
There is one more step required to learn if this process if foreground or background: The state value of
S+ must be decoded in
man ps under the heading of
PROCESS STATE CODE - which tells us:
S interruptible sleep (waiting for an event to complete)
+ is in the foreground process group
Consequently, we see from the
+ in the second character position that this process is running in the foreground. A background process may be listed with an
S in the first character position, and nothing in the second position. There are several other character combinations that indicate a background process; see this for a listing.
FWIW: This works on my Debian-based system (reported as version
ps from procps-ng 3.3.15), and in macOS 10.15 (which is descended from the BSD version of