2012-10-19 44 views
1

我基於在樣本程序生成在C於RHEL 4的Linux SMTP客戶端程序:適當的方式來傳遞C文件指針curl_easy_setopt功能

http://curl.haxx.se/libcurl/c/simplesmtp.html

每當所述消息體文本傳遞給該程序通過stdin,該程序正常工作。但是,當我嘗試將FILE指針傳遞給curl_easy_setopt()函數時,我遇到了段錯誤。註釋(來自示例程序simplesmtp.c)聲明可以將文件指針而不是stdin傳遞給curl_easy_setopt函數。從simplesmtp.c

/* You provide the payload (headers and the body of the message) as the 
* "data" element. There are two choices, either: 
* - provide a callback function and specify the function name using the 
* CURLOPT_READFUNCTION option; or 
* - just provide a FILE pointer that can be used to read the data from. 
* The easiest case is just to read from standard input, (which is available 
* as a FILE pointer) as shown here. 
*/ 
curl_easy_setopt(curl, CURLOPT_READDATA, stdin); 

相關的註釋部分,這些都是從與CURLOPT_VERBOSE選項設置控制檯錯誤線。

< 250 2.1.5 <[email protected]>... Recipient ok 
> DATA 
< 354 Enter mail, end with "." on a line by itself 
./r: line 5: 21282 Segmentation fault  ./mysmtpcli -r rcp.txt -m msg.txt 

BTW:./r是我的shell腳本,呼籲./mysmtpcli -r rcp.txt -m msg.txt

我的代碼

FILE *f_msg; 
f_msg = fopen(msg_file, "r"); 
if(!f_msg){ 
    fprintf(stderr, "Could not load message file: %s\n", msg_file); 
    return 1; 
} 

curl_easy_setopt(curl, CURLOPT_READDATA, f_msg); 

fclose(f_msg); 
的片段

注意:msg_file變量是從命令行參數填充的,並且是包含以下內容的有效文本文件:

主題:測試消息

這是測試消息!

當使用「cat msg.txt | ./mysmtpcli -r rcp.txt」通過stdin將相同的文件傳遞給程序時,程序正常執行。不過,這需要用stdin替換f_msg。

curl_easy_setopt(curl, CURLOPT_READDATA, f_msg); 

我是否正確傳遞FILE指針?

回答

1

是的,你確實傳遞了一個文件指針。儘管看起來你馬上關閉它。如果你這樣做,curl稍後會嘗試從該文件讀取並崩潰。只有在不再需要時才必須關閉它。

+0

我可能不明白內部。看起來你只需要用你的文件指針替換「stdin」,並且庫完成剩下的工作。我應該做什麼其他處理? – JTP

+0

@jtp:區別在於沒有人調用'fclose(stdin);'以便「文件」打開。然後一切正常。但是在你的代碼片段中,你可以調用'fclose(f_msg);',它會關閉文件,並且什麼都不起作用。你必須避免直到後來調用'fclose',當curl完成它的工作。 – 2012-10-19 00:31:57

+0

漂亮!後來我在代碼中移動了fclose語句,並且段錯誤消失了。我現在正在從服務器上得到一個「500 5.5.1 Command unrecognized:」,但電子郵件正在發送,我將繼續從這裏進行調試。謝謝。 – JTP