在 Web 服務中異步調用 Python 腳本

CGI 中須要調用一個 Python 腳本,腳本去更新執行 update 的 sql 語句,時間較長,超過了 Web 服務器的最大鏈接時間,所以須要使用異步調用腳本的方式。node

同步方式

char command[300] = "~/tools/read_emoji_text.py";
iRet = system(command);
MMJsonOutput *pOutResult = new MMJsonOutput;
pOutResult->GetResult()["errcode"] = iRet;
pOutResult->GetResult()["msg"] = "upload file success";`

很明顯,Python 腳本執行完後纔給請求返回數據linux

異步方式

if (0 == fork()) {
    char command[300] = "~/tools/read_emoji_text.py";
    iRet = system(command);
    _exit(127);
}
else {
    MMJsonOutput *pOutResult = new MMJsonOutput;
    pOutResult->GetResult()["errcode"] = iRet;
    pOutResult->GetResult()["msg"] = "upload file success";

    return pOutResult;
}

主進程直接返回數據,在子進程中去調用同步的 system 函數,執行 Python 腳本。這裏還可使用更底層的 execl 系統調用來執行腳本。sql

遇到的問題

使用異步的方式,iRet 的返回值一直爲 256,至關於 read_emoji_text.py 執行返回值爲 256 >> 8 = 1。出現這個錯誤的緣由是打開文件的路徑寫的是相對路徑,而二進制在執行時並非在這個路徑。服務器

def get_mark_data():
    file = open("~/tools/emoji_data")
    revise_list = []

參考

linux system函數的學習異步

System Return Code was 256函數

相關文章
相關標籤/搜索