I am writing the shell scripts to start a service on Linux.
I want to start a program, and save its pid to the pid file (so service can stop it again).
I also want to capture the first few (100, say) lines of its standard output to a file, and discard the rest (as there is a lot of output, so the file could get far too large if I saved it all).
I have tried the following code:
(program 2>&1 &
echo $! >flags/program.pid ) | head -n 200 >/jumbo/program/log &
However, after this is run, the log file is empty.
Could this be because there aren't a 100 lines yet?
** IMPORTANT ** I DO NOT want to capture the entire output of the process - I want to discard all but the first 100 or so lines, otherwise the disk will rapidly fill up.
I have read the alleged duplicate at Bash: Capture output of command run in background, and come up with the following proposed code:
exec 3< <(program 2>&1 &
echo $! >flags/program.pid )
(head -n 100 <&3 >program.log
cat <&3 >/dev/null)&
However, I don't understand the underlying mechanisms here, and would like to be reassured that this won't gobble up resources (it may be running for years at a time, as it is a service, and the program outputs a lot of data).
Also, obviously, suggestions for improvements welcome.