gpt4 book ai didi

linux - 用外部程序获取命令行上的内容

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

我想编写一个小程序来分析我当前在命令行上的输入,并像那些搜索引擎那样生成一些建议。

问题是外部程序如何获取命令行上的内容?例如

# an external program started and got passed in the PID of the shell below.
# the user typed something in the shell like this...

<PROMPT> $ echo "grab this command"

# the external program now get 'echo "grab this command"'
# and ideally the this could be done in realtime.

另外,我可以只修改当前命令行的内容吗?

编辑

bash 使用 libreadline 来管理命令行,但我仍然无法想象如何使用它。

最佳答案

您可以使用 c 编写自己的 shell 包装器。使用 popen 在进程中打开 bash,并使用 fgetcfputc 将数据写入进程和输出文件。

一个快速肮脏的 hack 可能看起来像这样(bash 不是在交互模式下启动的,但除此之外应该可以正常工作。--> 没有提示):

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>


pid_t pid;

void kill_ch(int sig) {
kill(pid, SIGKILL);
}

/**
*
*/
int main(int argc, char** argv) {
int b;
FILE *cmd = NULL;
FILE *log = NULL;

signal(SIGALRM, (void (*)(int))kill_ch);

cmd = popen("/bin/bash -s", "r+");
if (cmd == NULL) {
fprintf(stderr, "Error: Failed to open process");
return EXIT_FAILURE;
}
setvbuf(cmd, NULL, _IOLBF, 0);

log = fopen("out.txt", "a");
if (log == NULL) {
fprintf(stderr, "Error: Failed to open logfile");
return EXIT_FAILURE;
}
setvbuf(log, NULL, _IONBF, 0);

pid = fork();

if (pid != 0)
goto EXEC_WRITE;
else
goto EXEC_READ;


EXEC_READ:
while (1) {
b = fgetc(stdin);
if (b != EOF) {
fputc((char) b, cmd);
fputc((char) b, log);
}
}

EXEC_WRITE:
while (1) {
b = fgetc(cmd);
if (b == EOF) {
return EXIT_SUCCESS;
}
fputc(b, stdout);
fputc(b, log);
}

return EXIT_SUCCESS;
}

关于linux - 用外部程序获取命令行上的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38423422/

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