[英]Send Linux command from C program
I'm writing a C program to run in Linux shell. 我正在编写一个在Linux shell中运行的C程序。 Now I got a problem with such command.
现在我遇到了这样的命令问题。
#include <stdio.h>
void main()
{
char* command="history>>history";
system(command);
}
I want it to write the result of command "history" into a document, but it failed with a blank one. 我希望它将命令“ history”的结果写入文档,但是失败,并显示空白。
If I change it to "date>>history", current system time will be written into the document. 如果将其更改为“ date >> history”,则当前系统时间将写入文档中。
Is there any problem with "history>>history"? “历史>>历史”有什么问题吗? What should I do if I want to get that work?
如果我想得到那份工作该怎么办? Thanks!
谢谢!
The problem is that history
is not a real command but a shell builtin. 问题在于
history
不是真正的命令,而是内置的shell。 Thus you can't call it from a C program[1]. 因此,您不能从C程序[1]调用它。
Depending on the shell the user is using, you can instead get the history from ~/.bash_history
, ~/.zsh_history
and so on. 根据用户使用的外壳,您可以改为从
~/.bash_history
和~/.zsh_history
等获取历史记录。 Note however that zsh only write to this file at the end of a session. 但是请注意,zsh仅在会话结束时写入此文件。
[1] Well, you could theorically try system("bash -c history")
, but you won't get the actual history because the builtin isn't run in the context of the current session. [1]好吧,从理论上讲,您可以尝试
system("bash -c history")
,但是由于内置函数未在当前会话的上下文中运行,因此您将无法获得实际的历史记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.