用execv调用'ls' [英] Calling 'ls' with execv
本文介绍了用execv调用'ls'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是系统调用和C编程的新手,正在从事大学作业.
I am new to system calls and C programming and am working on my university assignment.
我想调用'ls'命令并让它打印目录.
I want to call the 'ls' command and have it print the directory.
我所拥有的:(我添加了注释,以便您可以看到通过每个变量看到的内容.
What I have: (I have added comments in so you can see what I see coming through each variable.
int execute( command* cmd ){
char full_path[50];
find_fullP(full_path, p_cmd);
//find_fullP successfully updates full_path to /bin/ls
char* args[p_cmd->argc];
args[0] = p_cmd->name;
int i;
for(i = 1; i < p_cmd->argc; i++){
args[i] = p_cmd->argv[i];
}
/*
* this piece of code updates an args variable which holds arguments
* (stored in the struct) in case the command is something else that takes
* arguments. In this case, it will hold nothing since the command
* will be just 'ls'.
*/
int child_process_status;
pid_t child_pid;
pid_t pid;
child_pid = fork();
if ( child_pid == 0 ) {
execv( full_path, args );
perror("fork child process error condition!" );
}
pid = wait( &child_process_status );
return 0;
}
我什么都没看见而且很困惑,知道吗?
I am not seeing anything happening and am confused, any idea?
推荐答案
这是使用execv
调用ls
的最小程序.注意事项
Here's the minimal program that invokes ls
using execv
. Things to note
-
args
的列表应将可执行文件作为第一个arg -
args
的列表必须以NULL终止 - 如果正确设置了
args
,则可以将args[0]
作为第一个参数传递给execv
- the list of
args
should include the executable as the first arg - the list of
args
must be NULL terminated - if the
args
are set up correctly, thenargs[0]
can be passed as the first parameter toexecv
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main( void )
{
int status;
char *args[2];
args[0] = "/bin/ls"; // first arg is the full path to the executable
args[1] = NULL; // list of args must be NULL terminated
if ( fork() == 0 )
execv( args[0], args ); // child: call execv with the path and the args
else
wait( &status ); // parent: wait for the child (not really necessary)
return 0;
}
这篇关于用execv调用'ls'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文