You can use:
ps h --ppid $$ | wc -l
to get the number of child processes from a bash script (remember this includes ps). So if you want to have 1000 processes you check to see if that returns 1001. If not fire them up with:
cmd &
so that they run as children of the current script (and therefore get included in the count.) You can then sleep for a bit, then check again in a loop forever. One thing to keep in mind is if you are spawning other processes you will need to modify the ps
command to filter the processes you want.
That first command is core piece of the puzzle, it should just be a little more until you have your script.
The CMD
output by ps
is either the process name or the arguments passed to the command (including the first argument argv[0]
). Though it bears some relation with the path of the executable, there's no guarantee for them to be linked.
On Linux:
print -r -- /proc/self/exe(:A)
On Darwin and Linux and possibly others:
lsof -ap"$$" -dtxt -Fn | sed '2!d;s/.//;q'
But I don't know how reliable it is.
Another heuristic:
print -r -- ${${0#-}:c:A}
$0
, like you see in the ps output contains the first argument that zsh
received (argv[0]
), or when passed a script as argument, that argument.
In the first case, typically, (by convention, there's no guarantee) that argv[0]
would be either a path including a /
(relative or absolute), or zsh
(something without /
) in which case the caller will have looked up zsh
in his $PATH
or his command hash table... If the path is relative, the above method will only work if the current directory has not changed since zsh was invoked. If there's no /
, the method will only work if zsh
is looking up the executable the same way as the caller did.
In the case of a script, it's the path of the script that will be returned instead of that of the interpreter (contrary to the first two solutions).
Best Answer
Try this:
Or if you don't want to parse the output of
ls
, just do:or