gpt4 book ai didi

c - 进程返回 -1 (0xFFFFFFFF)

转载 作者:太空宇宙 更新时间:2023-11-04 06:20:12 28 4
gpt4 key购买 nike

#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 制定一个概念,我让它输出您输入到用户主目录中的文件中的每个命令。这还没有完全完成,但我一次只做一部分。当我向“shell”输入任何内容时,它崩溃了。 Codeblocks 告诉我“进程返回 -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 来附加到文件首先是一个坏主意。如果输入包含 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);

(再次省略错误检查。)

关于c - 进程返回 -1 (0xFFFFFFFF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36826764/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com