Hi marsd,
I don't think your code is answering the original question of this thread. Yes, your example does fork a child process, but when you make the call
, this actually spawns a third and fourth process. The fourth process is the PID that
SmileeTiger wanted to capture and you code doesn't capture this. You're code is only capturing the PID of the child that makes that
call.
For example, I've changed your code to have a
of 2, and I've changed the
Code:
system("ps -a");
call to a
Code:
system("ps -f");
so it will only report my processes. Running it with the command line parameter
, I get the following...
[tt]
$ ./marsd 'sleep 2'
UID PID PPID C STIME TTY TIME CMD
sambones 20312 20310 0 10:42:34 pts/0 0:00 sh -c sleep 2
sambones 20311 20309 0 10:42:34 pts/0 0:00 sh -c ps -f
sambones 20310 20309 0 10:42:34 pts/0 0:00 ./marsd sleep 2
sambones 20278 16752 0 10:42:17 pts/0 0:00 ksh
sambones 16752 16750 0 09:45:53 pts/0 0:00 -ksh
sambones 20313 20312 0 10:42:34 pts/0 0:00 sleep 2
sambones 20309 20278 0 10:42:34 pts/0 0:00 ./marsd sleep 2
Still waiting!
Child 20310, parent 20309
Exit Status 0
$
[/tt]
Your parent and child are PID
20309 and
20310 and are running the identical command, which is what a fork does. The process created by the
call is a bourne shell with PID
20312 which then creates a process that actually does the command of
with a PID of
20313. You're code isn't capturing the PID of
20313, which is what
SmileeTiger was looking for. This is four processes and it still isn't giving the parent the PID of the process he wants the PID for. My example is only two processes, and does give the parent the correct PID of the child process he wants to track.
Also, the redundant process from your fork isn't buying you anything in this case. In any real world application where the processes are more complicated, the redundant processes cause problems. Also fork() and exec() are the cleanest way to create a daemon.
Hope this helps.