unix pid

Richard A. O'Keefe <>
Mon Jul 11 01:01:33 CEST 2005

Michael McDaniel <> wrote:
	Perhaps I am misunderstanding the Erlang documentation.

Actually, no.  It's the UNIX sheels you're misunderstanding.
	os:cmd/1 says...
	cmd(Command) -> string()
	Command = string() | atom()
	Executes Command in a command shell of the target OS and returns
	the result as a string.

That is, it captures the STANDARD OUTPUT of the command, just as
backquote does in the shell.  So what's written to the standard output?

	If I do the following from my (Linux) system prompt
	$ sleep 97 &
	[3] 11702
	Since the Pid is returned as a string from the command prompt, I would expect the following
	from within Erlang to return the Pid also, though it does not.
Much depends on what shell you run and how it is invoked.
For example, you get the [3] job number from the C shell (csh) or jsh,
but not from the Bourne shell (sh).  More to the point, look at this:

	f% sh
	$ sleep 1 &
	$ (sleep 1 &)>/tmp/foo.out
	$ cat /tmp/foo.out
	$ sh -c "sleep 10 &"
	$ ps
	  4008 pts/6    0:06 csh
	 18416 pts/6    0:00 ps
	 18415 pts/6    0:00 sleep
	 18398 pts/6    0:00 sh

Did you notice where 'sh -c "<command>"' produced NO output?
Now let's try it from C:

	f% cat foo.c
	extern int system(char const *);

	int main(void) {
	    (void) system("sleep 10 &");
	    return 0;
	f% cc foo.c
	f% a.out
	f% ps
	f% ps
	  4008 pts/6    0:06 csh
	 18445 pts/6    0:00 ps
	 18444 pts/6    0:00 sleep


The point here is that when a shell creates another process in response
to an "&" in the command, it writes the PID (plus, in the case of csh,
the job number) if and only if it thinks there is a human being watching
the output; if it thinks a program is watching the output, the PID is
*not* written.

What's the answer?  You will have to explicitly write out the process
number using $! .

	$ sh -c "sleep 10 &  
	> echo $!"

Or in Erlang:
	1> os:cmd("sleep 10 &\necho $!").

More information about the erlang-questions mailing list