Page 1 of 1

Wanting stdout, stderr and return code of shell commands

Posted: Tue Nov 08, 2011 9:37 pm
by Ishpeck
When I use exec or ! to run a shell command, I want to get strings containing the contents of stdout and stderr (even if empty) as well as the exit code of the program.

I could direct the output in the command like so:
(! "ls 2>/tmp/err >/tmp/out")

And then just read those files but that seems horribly crufty.

Now exec gives me stdout but I still want exit code and stderr.

Is there a better way to see what is happening with the programs I run?

Re: Wanting stdout, stderr and return code of shell commands

Posted: Mon Jun 02, 2014 5:44 pm
by jef
Old post but it's worth a reply as I was also looking for a solution.
process and waitpid can be used. An example returning stdout/stderr
combined and the return code of the command:

Code: Select all

(define (exec2 cmd)
  (let ((pid) (out_r) (out_w) (output) (data))
    (map set '(out_r out_w) (pipe))
    (setq pid (process cmd 0 out_w))
    (close out_w)
    (while (read out_r data 1024)
           (extend output data))
    (list output (>> ((wait-pid pid) 1) 8))))
Examples of the execution of a successful and a failed command:

Code: Select all

> (exec2 "/bin/echo pouet")
("pouet\n" 0)

> (exec2 "/bin/ls /root")
("/bin/ls: cannot open directory /root: Permission denied\n" 2)

Re: Wanting stdout, stderr and return code of shell commands

Posted: Wed Jun 04, 2014 5:41 am
by ralph.ronnquist
It depends on the platform of course. With bash and similar, you could also have

Code: Select all

(define (exec2 cmd) (exec (string cmd " 2>&1 ; echo $?"))
That will nicely parse and deliver the output (stdout and stderr) as a list of lines, with the addition of the return code as an additional string element at the end.