[英]Why does the system call system() not work as intended in this C program?
這是一個 C 程序,它將兩個進程(父進程和子進程)連接到一個 pipe。子進程運行一個 python 腳本,該腳本過濾 RSS 提要中的一個短語(字符串),父進程捕獲 URL 並在瀏覽器中打開它. 這是源代碼
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
void open_url(char *url)
{
char launch[255];
sprintf(launch, "cmd /c start %s", url);
system(launch);
}
void error_msg(char *msg)
{
printf("msg: %s\n", msg);
fprintf(stderr, "%s: %s\n", msg, strerror(errno));
exit(1);
}
int main(int argc, char* argv[])
{
char *phrase = argv[1];
char *vars[] = {"RSS_FEED=https://rss.app/feeds/tUpJh41L1MCpL3dl.xml", NULL};
int fd[2];
if(pipe(fd) == -1)
error_msg("Can't open a pipe");
pid_t pid;
pid = fork();
if (pid == -1)
error_msg("Can't fork process");
if (!pid)
{
dup2(fd[1], 1);
close(fd[0]);
if (execle(
"C:/Users/LENOVO/AppData/Local/Programs/Python/Python310/python",
"C:/Users/LENOVO/AppData/Local/Program/Python/Python310/python",
"./rssgossip.py", "-u", phrase, NULL, vars) == -1
)
error_msg("Can't run script");
}
dup2(fd[0], 0);
close(fd[1]);
char line[255];
while(fgets(line, 255, stdin))
{
if (line[0] == '\t')
open_url(line + 1);
}
return (0);
}
該程序編譯沒有任何錯誤,但是當父級在 open_url() 中調用 system(launch) 時,問題就出在這里。 令人驚訝的是,它只執行存儲在 launch 中的命令的第一部分,即“cmd /c start”,而忽略了 url。更令人驚訝的是,當我通過一個簡單的 printf 語句 printf("%s", launch) 調試程序時,我將 printf 語句的相同 output 替換為啟動變量,而不是 system(launch) -> system("cmd /c start 'url'") 並按預期在瀏覽器中執行 url。
編輯:這是該程序中使用的 python 腳本 (rssgossip.py) 的直接下載鏈接,如果您想嘗試它以更清楚地了解我正在嘗試做的事情。 我建議您首先將腳本作為 Python 腳本運行(使用 Python 解釋器)以了解該腳本的實際作用。 要將其作為 Python 腳本運行,您需要定義 RSS_FEED 環境變量並為其分配一個 rss 提要 RSS_FEED=<rss_feed_url>(您可以使用此程序中使用的 rss_feed_url),最后將其作為 python rssgossip.py '<任何短語>'
當我嘗試這段代碼並且運行良好時
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
void open_url(char *url)
{
char launch[255];
sprintf(launch, "cmd /c start "" %s", url);
printf("%s",launch);
system(launch);
}
int main()
{
char url[] = "C:/emu8086/emu8086.exe";
open_url(url);
}
可能是你輸入的參數有問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.