简体   繁体   中英

Send Linux command from C program

I'm writing a C program to run in Linux shell. 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.

If I change it to "date>>history", current system time will be written into the document.

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. Thus you can't call it from a C program[1].

Depending on the shell the user is using, you can instead get the history from ~/.bash_history , ~/.zsh_history and so on. Note however that zsh only write to this file at the end of a session.

[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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM