首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用execv调用“ls”

使用execv调用“ls”
EN

Stack Overflow用户
提问于 2015-02-14 04:10:57
回答 1查看 21.1K关注 0票数 3

我是系统调用和C编程的新手,现在正在做我的大学作业。

我想调用“ls”命令,让它打印目录。

我所拥有的:(我在中添加了注释,这样您就可以看到我通过每个变量看到的内容。

代码语言:javascript
复制
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;
}

我没有看到任何事情发生,我很困惑,你知道吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-14 04:45:32

下面是使用execv调用ls的最小程序。注意事项

  • args列表应包括可执行文件作为第一个参数
  • args列表必须以NULL终止
  • 如果args设置正确,则<args>d11>可以作为第一个参数传递给code

代码语言:javascript
复制
#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;
}
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28507950

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档