Operating System - HP-UX
1834711 Members
2352 Online
110069 Solutions
New Discussion

How to get the process id of a process?

 
SOLVED
Go to solution
Shashibhushan Gokhale
Occasional Contributor

How to get the process id of a process?

Hi,

I am trying to get the process id of a process I try to start in the background.

I had come to know about a technique of using $! to get the status of last spawned process.
The above method works for commands like sleep.

When I do $! for my program I get a value, but when I do ps -ef the process id for the process in the listing is greater than the value returned by $! by 1.
For additional information I am setting setsid() in my program. Does it has anything to do with it.

Can anyone help me out.

Thanks in advance.
Shashibhushan GOkhale
7 REPLIES 7
Ian Dennison_1
Honored Contributor

Re: How to get the process id of a process?

Try using "$$" to obtain the current Process ID.

Null points if I am not the first to suggest this pse.

Share and Enjoy! Ian
Building a dumber user
Dietmar Konermann
Honored Contributor
Solution

Re: How to get the process id of a process?

Maybe your program does additional fork()s, e.g. to daemonize itself? In this case it would not be the "direct" child of your shell, i.e. no child the shell can know anything about.

Either you seek the process using ps or you add some code to the program that writes its own PID to some status file, just like syslogd uses /var/run/syslog.pid.

Best regards...
Dietmar.
"Logic is the beginning of wisdom; not the end." -- Spock (Star Trek VI: The Undiscovered Country)
Shashibhushan Gokhale
Occasional Contributor

Re: How to get the process id of a process?

HI Dietmar,

You are absolutely right.
I am using fork() to daemonize itself.

Thanks,
Shashibhushan
Bill McNAMARA_1
Honored Contributor

Re: How to get the process id of a process?

brise:root /# jobs
[2] + Running sleep 6000 &
brise:root /# jobs -p %2
21854

brise:root /# ps -ef | grep 21854
root 22308 21624 1 07:07:38 pts/tb 0:00 grep 21854
root 21854 21624 0 07:06:09 pts/tb 0:00 sleep 6000

Later,
Bill
It works for me (tm)
Dietmar Konermann
Honored Contributor

Re: How to get the process id of a process?

Bill,
after running setsid() the program is the leader of a new process group. So I doubt, that jobs -p is able to find anything (didn't test this myself).

Best regards...
Dietmar.
"Logic is the beginning of wisdom; not the end." -- Spock (Star Trek VI: The Undiscovered Country)
John Meissner
Esteemed Contributor

Re: How to get the process id of a process?

to get the process number (pid) of a process you last ran try:

echo $!
or
echo $?
All paths lead to destiny
Bill McNAMARA_1
Honored Contributor

Re: How to get the process id of a process?

okay Dietmar,
I just read the first line!
It works for me (tm)