簡體   English   中英

進程返回-1(0xFFFFFFFF)

[英]Process returned -1 (0xFFFFFFFF)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main() {
 printf("Transactional Shell Command Test.\n");
 while(1) {
  printf("Queue:");
  char input[500];
  fgets (input, 500, stdin);
  if(strstr(input, "qb-write")){
    printf("These are the commands you have queued:\n");
    FILE *cmd = popen("cat /home/$USER/.queueBASH_transactions", "r");
    char buf[256];
    while (fgets(buf, sizeof(buf), cmd) != 0) {
      printf("%s\n",buf);
    }
    pclose(cmd);
  }
  system(strncat("echo ",strncat(input," >> /home/$USER/.qb_transactions",500),500));
  usleep(20000);
 }

 return 0;
}

我正在嘗試為事務性外殼程序創建一個概念,並且讓它將您輸入的每個命令輸出到用戶主目錄中的文件中。 還沒有完全完成,但是我一次只做一部分。 當我在“ shell”中輸入任何內容時,它就會崩潰。 代碼塊告訴我“進程返回-1(0xFFFFFFFF)”,然后告訴我有關運行時的常規信息。 我在這里做錯了什么?

strncat將附加到其第一個參數,因此您需要將一個可寫緩沖區作為第一個參數傳遞給它。 您傳遞的是字符串文字( "echo " ),取決於您的編譯器和運行時環境,該文字可能會覆蓋內存中不可預測的部分,或者因為試圖寫入只讀內存而崩潰。

char command[500];
strcpy(command, "echo ");
strncat(command, input, sizeof(command)-1-strlen(command));
strncat(command, " >> /home/$USER/.qb_transactions", sizeof(command)-1-strlen(command));
system(command);

與其他代碼一樣,我省略了錯誤檢查,因此如果該命令不適合緩沖區,該命令將被截斷。 還要注意,重復調用strncat效率很低,因為它們涉及多次遍歷字符串以確定其結尾。 使用返回值並跟蹤剩余的緩沖區大小會更有效,但是我將其留作后續練習。

當然,首先調用shell附加到文件是個壞主意。 如果輸入包含外殼特殊字符,則將對它們進行評估。 您應該打開日志文件並直接對其進行寫入。

char log_file[PATH_MAX];
strcpy(log_file, getenv("HOME"));
strncat(log_file, "/.qb_transactions", PATH_MAX-1-strlen(log_file));
FILE *log_file = fopen(log_file, "a");
…
while (1) {
    …
    fputs(cmd, log_file);
}
fclose(log_file);

(再次,將省略錯誤檢查。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM