将变量传递给popen命令

时间:2012-06-22 07:29:23

标签: c linux terminal openssl 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

2 个答案:

答案 0 :(得分: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 :(得分:1)

如果参数包含任何空格,引号或其他特殊字符,则构造带有snprintf的命令字符串将会中断。

在Unix平台上,您应该使用pipe来创建管道,然后使用posix_spawnp启动子流程,将子流程的stdout连接到管道的输入端posix_spawn_file_actions_adddup2

相关问题