unix pid

Michael McDaniel <>
Mon Jul 11 01:38:20 CEST 2005


On Mon, Jul 11, 2005 at 11:01:33AM +1200, Richard A. O'Keefe wrote:
> 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()
> 	
> 	Types:
> 	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 &
> 	18399
> 	$ (sleep 1 &)>/tmp/foo.out
> 	$ cat /tmp/foo.out
> 	18407
> 	$ sh -c "sleep 10 &"
> 	$ ps
> 	   PID TTY      TIME CMD
> 	  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
> 	   PID TTY      TIME CMD
> 	  4008 pts/6    0:06 csh
> 	 18445 pts/6    0:00 ps
> 	 18444 pts/6    0:00 sleep
> 
> Again, NO OUTPUT.
> 
> 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 $!"
> 	18509
> 	$ 
> 
> Or in Erlang:
> 	1> os:cmd("sleep 10 &\necho $!").
> 	"18525\n"
> 
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Wonderful!  Thank you for the explanation and the solution.

~Michael



More information about the erlang-questions mailing list