2012-06-22 83 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輸入端。