capture the process id when starting a background process

Hello all,
How do I start a background process and save the process id to a file on my system. For example %wait 5 & will execute and print the process id. I can't figure out how to get it to a file. I've tried: > filename 0>filename 1>filename.
Any assistance is most appreciated.
Thanks,
Jim Leavitt

Sounds like it "could be homework, but I will help none the less.

ioscan -fnC disk & ps -aef |grep ioscan|grep -v ps | awk '{ print $2 }' > cap.PID

This may capture the PID of the ps command, but it works. Even though it is crude.

:cool:

If you use:

ps -ef | grep "[i]oscan" | awk '{print $2}'

then you will not have to worry about capturing the PID of ps -- a handy side effect of using the square brackets.

Thanks for the help, it's close but it doesnt work. This isn't homework, and I should know how to do this myself. I don't. We've got a socket server we want to start and kill nightly. The only way I can think of is to keep the pid around so I know what to kill at night. Any additional help is most appreciated!
Thanks,
Jim Leavitt
Romac Industries, Inc.:slight_smile:

Can you modify the source to the server? If so just have it write its PID to a file somewhere.

Did you try 2>filename?
Also, how is it started?
Some shells, like bash, will store the value of the previous process ID. In bash, I believe it is $PPID.
I can't remember for sure though... anyone else know?

I think his main problem is that he wants to run this in the background. So, when the process kicks off nothing prints to the screen.

I was trying to capture the PID with ps because 2> won't work because there is nothing to capture. Although the " [1] 12345 " appears on the screen, it is after the process is kicked to the background.

It would be easy to do this except that he is trying to run it in the background.

The only thing I can see is to grep for the PID after you kick off the background process.

In ksh, $! gives the process ID of the last background command invoked ($PPID is the parent PID).

somecommand &
echo $! > somecommand.pid

To save the PID of script.sh to pid

script.sh & echo $! > pid

This should work in sh, ksh and bash, but not csh.

Thanks Jimbo, moderator, that did it. Very much appreciated, thank you all for your responses.
Jim Leavitt

$? gives the PID of the last process.

But if many processes start consequently,I'm not sure that we
can get the one we search.