DSM: sys.popen function to exec external program

example:
  sys.popen($myresult="/bin/ls wav/*");
  logVars(2);
sayer/1.4-spce2.6
Stefan Sayer 16 years ago
parent 46242169a3
commit 042b073780

@ -34,6 +34,7 @@
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
SC_EXPORT(MOD_CLS_NAME);
@ -45,7 +46,7 @@ MOD_ACTIONEXPORT_BEGIN(MOD_CLS_NAME) {
DEF_CMD("sys.unlink", SCUnlinkAction);
DEF_CMD("sys.unlinkArray", SCUnlinkArrayAction);
DEF_CMD("sys.tmpnam", SCTmpNamAction);
DEF_CMD("sys.popen", SCPopenAction);
} MOD_ACTIONEXPORT_END;
MOD_CONDITIONEXPORT_BEGIN(MOD_CLS_NAME) {
@ -54,7 +55,6 @@ MOD_CONDITIONEXPORT_BEGIN(MOD_CLS_NAME) {
return new FileExistsCondition(params, false);
}
// ahem... missing not?
if (cmd == "sys.file_not_exists") {
return new FileExistsCondition(params, true);
}
@ -257,3 +257,46 @@ EXEC_ACTION_START(SCTmpNamAction) {
sc_sess->SET_ERRNO(DSM_ERRNO_OK);
}
} EXEC_ACTION_END;
CONST_ACTION_2P(SCPopenAction, '=', false);
EXEC_ACTION_START(SCPopenAction) {
string dst_var = par1;
if (dst_var.length() && dst_var[0]=='$')
dst_var = dst_var.substr(1);
string cmd = resolveVars(par2, sess, sc_sess, event_params);
DBG("executing '%s' while saving output to $%s\n",
cmd.c_str(), dst_var.c_str());
char buf[100];
string res;
FILE* fp = popen(cmd.c_str(), "r");
if (fp==NULL) {
throw DSMException("sys", "type", "popen", "cause", strerror(errno));
}
size_t rlen;
while (true) {
rlen = fread(buf, 1, 100, fp);
if (rlen < 100) {
if (rlen)
res += string(buf, rlen);
break;
}
res += string(buf, rlen);
}
sc_sess->var[dst_var] = res;
int status = pclose(fp);
if (status==-1) {
throw DSMException("sys", "type", "pclose", "cause", strerror(errno));
}
sc_sess->var[dst_var+".status"] = int2str(status);
DBG("child process returned status %d\n", status);
} EXEC_ACTION_END;

@ -39,4 +39,5 @@ DEF_ACTION_2P(SCRenameAction);
DEF_ACTION_1P(SCUnlinkAction);
DEF_ACTION_2P(SCUnlinkArrayAction);
DEF_ACTION_1P(SCTmpNamAction);
DEF_ACTION_2P(SCPopenAction);
#endif

@ -0,0 +1,17 @@
-- test popen
import(mod_sys);
import(mod_utils);
initial state START
enter {
log(1,"Got into START state.");
sys.popen($myresult="/bin/ls wav/*");
logVars(2);
utils.splitStringCR($myresult);
logVars(2);
stop(true);
};
transition "error executing" START - exception; test(#type==popen) / logParams(1); stop(true) -> END;
transition "error closing" START - exception; test(#type==pclose) / logParams(1); stop(true) -> END;
state END;

@ -7,6 +7,16 @@ Actions:
Array version of unlink (prefix/filename_0 .. prefix/filename_$filename_size)
sys.tmpnam(string varname)
sys.popen($var="command")
execute a command (using popen) and save result in $var
example:
sys.popen($myfiles="/bin/ls wav/*");
throws exceptions
#type=="popen", #cause==reason if fails to exec
#type=="pclose", #cause==reason if fails to close pipe
Conditions:
sys.file_exists(string fname)
sys.file_not_exists(string fname)

Loading…
Cancel
Save