【问题标题】:Calling 'ls' with execv用 execv 调用 'ls'
【发布时间】:2015-04-14 23:42:33
【问题描述】:

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

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

我所拥有的:(我添加了 cmets,因此您可以看到我通过每个变量看到的内容。

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;
}

我没有看到任何事情发生并且很困惑,有什么想法吗?

【问题讨论】:

  • 使用opendirreaddirclosedir而不是使用外部程序
  • 添加日志记录(只打印东西就可以了)以了解您获得了多远以及变量是否持有您认为它们持有的值。或者使用调试器。
  • 你的args 数组应该以NULL 结束。见man execv
  • 如果作业是打印一个目录,我希望它得到更高的分数。
  • 为什么不改变p_cmd-&gt;argv[] 的表示,让p-&gt;cmd_argv[0] 是程序名呢?然后你就不必复制了。您可以只使用该 argv 对象。不要忘记argv[argc] 必须是一个空指针。具有 N 个参数的程序的 argv 需要 N+2 个元素。一个用于程序名称,N 用于参数,一个用于终止数组的空指针。如果你不终止数组,那么/bin/ls 可能会在argv[1] 中找到一个完整的垃圾指针(所以ls 崩溃),或者一个指向垃圾数据的指针(看起来像一个找不到的文件)。

标签: c fork system ls


【解决方案1】:

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

  • args 列表应包含可执行文件作为第一个参数
  • args 的列表必须以 NULL 结尾
  • 如果args设置正确,那么args[0]可以作为第一个参数传递给execv

#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;
}

【讨论】:

    猜你喜欢
    • 2019-05-10
    • 2017-03-10
    • 1970-01-01
    • 2013-10-09
    • 2018-09-09
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多