2012-06-22 81 views
2

我需要将一个字符串变量传递给一个popen命令,该命令是为了对一段加密数据进行描述而创建的。我需要使用的代码段是:将一个变量传递给popen命令

char a[]="Encrypted data"; 
popen("openssl aes-256-cbc -d -a -salt <a-which is the data i have to pass here>","r"); 

我该怎么做才能将此变量传递到命令中。我尝试过:

popen("openssl aes-256-cbc -d -a -salt %s",a,"r"); 

但在编译时显示错误,表明popen传递的参数太多。请帮忙。提前致谢。 操作平台:Linux

回答

4

使用snprintf来构造传递给popen的命令字符串。

FILE * proc; 
char command[70]; 
char a[]="Encrypted data"; 
int len; 
len = snprintf(command, sizeof(command), "openssl aes-256-cbc -d -a -salt %s",a); 
if (if len <= sizeof(command)) 
{ 
    proc = popen(command, "r"); 
} 
else 
{ 
    // command buffer too short 
} 
+1

并检查'snprintf()'是否没有截断命令? –

+0

什么时候编写一个终止NUL的具体原因,当snprintf会这样做? – SuperSaiyan

+0

根据(适当的)意见进行编辑。 – MByD

1

构建命令字符串snprintf如果参数包含空格,引号或其他特殊字符将打破。

在Unix平台上,你应该使用pipe创建管道,然后用posix_spawnp启动子,子进程的标准输出连接到管与posix_spawn_file_actions_adddup2输入端。