在LINUX下如何获得登录用户运行的SHELL命令?

WAKU 2008-09-01 09:29:30
比如用户运行如下命令:
#ls
我就能取到ls

运行
#ls -l > a.txt
我就能取到#ls -l > a.txt

用户使用上方向键运行以前的命令,甚至使用!符号运行HISTORY里的命令,也能正确取得
类似SHELL解析命令的功能,请问如何实现?
...全文
174 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
yangzhifu 2008-09-02
  • 打赏
  • 举报
回复
运行 ls 是到你的PATH指定的路径中寻找可以执行的文件(当然是从当前文件开始查找,如果你当前文件里面有ls可执行文件就运行这么命令)

运行
#ls -l > a.txt
我就能取到#ls -l > a.txt

这个是shell或者系统帮你把运行的命令记录下来而已(具体的文件就在你的用户家目录下的bash_history中)
和内存没有关系的!

如下有一个自己设计的psh () 是关于shell设计的,主要是处理输入的命令,没有编程功能!

/*
* psh2.c
* solves the 'one-shot ' porblen of version 0.1
* uses execvp () , but fork () s first so that the
* shell waits around to perform another command
* new Problem : shell catches signals , runvi ,Press ^s
*/

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


#define MAXARGS 20
#define ARGLEN 100
int main ()
{

char *arglist[MAXARGS + 1] ;
char argbuf[ARGLEN ] ;
int numargs =0 ;
char *makestring (char *buf) ;
void execute (char *list[] ) ;

while ( numargs < MAXARGS )
{
printf (" arg[%d]? \n",numargs ) ;
if ( fgets ( argbuf , ARGLEN , stdin ) && *argbuf != '\n' )
{
if ( strncmp ( argbuf , "quit" , 4 ) == 0 )
exit ( 1 ) ;
else
arglist[numargs++] = makestring ( argbuf );
}

else
{
if ( numargs > 0 )
arglist[numargs] =NULL ;
execute ( arglist ) ;
numargs =0 ;
}
}
return 0 ;
}

void execute ( char *list[] )
{
int pid , exitstatus ;

pid = fork () ;
switch ( pid ) {
case -1 : perror ( " fork feld " ) ; exit (1 ) ;
case 0 :
execvp ( list[0] , list ) ;
perror ( "execute error " ) ;
exit ( 2 ) ;
default :
while ( wait ( & exitstatus ) !=pid ) ;
printf ( " child exit whith status %d %d \n" , exitstatus>>8 , exitstatus &0x377 ) ;
}

}

char *makestring ( char *buf )
{

char *cp ;
int len ;

len = strlen( buf ) ;
buf [len-1 ] = '\0' ; /*here is very improtant , if buf[len ] , it will include the '\n' */

cp = ( char * ) malloc ( len +1 ) ;
if ( cp == NULL )
{
perror ( " malloc erro " ) ;
exit ( 2 ) ;
}

strcpy ( cp , buf ) ;

return cp ;
}

realdragon2 2008-09-02
  • 打赏
  • 举报
回复
帮顶~
快乐田伯光 2008-09-02
  • 打赏
  • 举报
回复
这玩意跟内核没有任何关系

[Quote=引用 3 楼 air_snake 的回复:]
引用 1 楼 wuyu637 的回复:
在一个config文件里,做了记录。

简单的说就是把你用过的命令保存了起来,启动的时候加载到内存,内存中的数据还会跟你使用情况改变更新。退出的时候再保存到config文件里


应该就是这样的。
自己要实现的话。可以参考内核的实现。
[/Quote]
air_snake 2008-09-02
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wuyu637 的回复:]
在一个config文件里,做了记录。

简单的说就是把你用过的命令保存了起来,启动的时候加载到内存,内存中的数据还会跟你使用情况改变更新。退出的时候再保存到config文件里
[/Quote]

应该就是这样的。
自己要实现的话。可以参考内核的实现。
wuyu637 2008-09-01
  • 打赏
  • 举报
回复
在一个config文件里,做了记录。

简单的说就是把你用过的命令保存了起来,启动的时候加载到内存,内存中的数据还会跟你使用情况改变更新。退出的时候再保存到config文件里
WAKU 2008-09-01
  • 打赏
  • 举报
回复
自己顶一下

23,125

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧