![](/img/trans.png)
[英]Linux C: Shell-like environment - for individual execution - of C commands? (C interpreter)
[英]Remote execution of shell commands
我是從這里拉我的頭發。 我正在嘗試為我的IRC機器人創建遠程shell執行,但是,當我使用諸如“ ls”或“ cd”之類的命令時,卻得到了“:not found”的返回,但是,其他命令諸如mkdir或回聲似乎工作正常。 當我對命令進行硬編碼時,也是如此,我得到的輸出與應有的完全一樣。
誰能看到原因? 這是我的代碼:
FILE *fp;
int status;
char path[1035];
/* Open the command for reading. */
fp = popen(ptr1, "r"); // hard code command and it works ????fp = popen("/bin/ls /etc/", "r");
printf("%s", ptr1);//check received command (debugging)
if (fp == NULL) {
printf("Failed to run command\n" );
出於道德原因刪除了一些代碼。
我將從您的錯誤消息中猜測,您要傳遞給popen的字符串中有一個虛假的回車符。 因此,您實際上是在打電話,例如popen("ls\\r", "r");
失敗,並顯示錯誤消息ls\\r: not found
。 當您打印該錯誤消息時,回車導致它跳回到該行的開頭,看起來像: not found
回車是臭名昭著的奇怪錯誤的來源,因為它們不是外殼的空白,但是在打印出來時看不到它們。
在上面的代碼中,ptr1沒有初始化。 假設ptr1是您的命令並且在其他地方填充,您是否檢查過字符串是否以零結尾在正確的位置? 即使使用printf,某些不可打印的字符也可能位於字符串的結尾和零終止之間,從而使您擁有“ ls___”。 只需對ptr1長度進行快速檢查即可:
printf("%s : %lu", ptr1, strlen(ptr1));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.