7/13 how do i pass variables to the system in C ? e.g.
system("echo input is %s", argv[1]);
results in "input is %s" but I want the system to see argv[1]
(I know i can just use printf, but not for what i really want to do).
\_ sprintf into array, pass array to system?
\_ so write your own function that takes a variable number of
arguments, allocates memory, concatenates the arguments together,
calls system on the combined string, and frees the memory. That
wasn't so hard, was it? or, depending on what platform you're
using, there may be some non-ANSI functions that do what you want.
\_ Something like the following should work on Linux/BSD:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
int fsystem(const char *cmd, ...) {
va_list ap;
char buf[BUFSIZ];
int ret;
vsnprintf(buf,sizeof(buf),cmd,ap);
if (cmd == NULL)
return system(buf);
return -1;
va_start(ap,cmd);
ret = vsnprintf(buf,sizeof(buf),cmd,ap);
va_end(ap);
return (ret > sizeof(buf) ? -1 : system(buf));
}
\_ except for the obvious buffer overflow this code is
susceptible to. A very dangerous thing to do, especially
when passing things off to system(). One should include
sanity checking to keep someone from passing on args like
" ; /bin/rm -rf /"
\_ I see no buffer overflow as long as vsnprintf
is correctly implemented. Of course system()
still sucks.
\_ It is an example. He would be a fool to use it
exactly as written without argument validation
and command checking. BTW what buffer overflow are
you talking about? I'm using a fixed size buffer,
and I'm passing sizeof(buf) to vsnprintf, which
is the safe way of doing this AFAIK. Is the problem
in the fact that the return code from vsnprintf
isn't checked? If so, I've just added that.
\_ I was hasty about the overflow, missing that it was
vsnprintf that was used, and thinking of vsprintf
instead, which would make it susceptible. The
point about argument checking still stands. |