用execv调用'ls'

asd*_*sdf 3 c fork ls system

我是系统调用和C编程的新手,正在完成我的大学任务.

我想调用'ls'命令并让它打印目录.

我有什么:(我添加了评论,这样你就可以看到我看到的每个变量.

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;
}
Run Code Online (Sandbox Code Playgroud)

我没有看到任何事情发生,我很困惑,任何想法?

use*_*109 9

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

  • args应该包含可执行文件的列表作为第一个arg
  • 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;
}
Run Code Online (Sandbox Code Playgroud)