使用execv(C语言)从linux命令提示符运行命令 [英] Using execv (C language) to run commands from a linux command prompt

查看:510
本文介绍了使用execv(C语言)从linux命令提示符运行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我唯一困惑的是如何使用第一个参数将execv设置为当前工作目录.我都尝试过."和〜",两者均未在屏幕上执行任何操作;与"/"相同.和"/〜".我对如何让execv运行如下内容感到困惑:

The only part I am confused on thus far is how to set up execv with the first parameter as the current working directory. I've tried both "." and "~", neither are executing anything to the screen; same for "/." and "/~". I'm confused on how to have execv run something like this:

$ ./prog ls -t -al

在程序执行后(存储在argv中)在当前目录或与文件所在的目录相同的目录中执行命令(根据使用该文件的人而有所不同).

And have it execute the commands after the program execution (which are stored into argv) in the current directory, or the same directory as the file is in (which will vary based on who is using it.)

我的代码:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

void main(int argc, char *argv[])
{
    int pid;
    int count = 0;
    char *argv2[argc+1];

    for(count = 0; count < argc-1; count++){
        argv2[count] = argv[count+1];
        printf("Argv2: %s\n", argv2[count]);  //just double checking
        argv2[argc-1] = NULL;
    }

    pid = fork();
    if(pid == 0){
        printf("Child's PID is %d. Parent's PID is %d\n", (int)getpid, (int)getppid());
        execv(".", argv2);       //<---- confused here
    }
    else{
        wait(pid);
        exit(0);
    }
}

一些示例输出:

$ ./prog ls -t -al
Argv2: ls
Argv2: -t
Argv2: -al
Child's PID is 19194. Parent's PID is 19193

推荐答案

我猜想 execv 是必需的. execvp 更好,因为它将在PATH设置中查找命令.

I guess execv is what is required to be used. execvp is a lot nicer since it will look for commands in your PATH setting.

execv(".", argv2);       //<---- confused here

...

#include <errno.h>
#include <string.h>
if ( execv(argv2[0],argv2) )
{
    printf("execv failed with error %d %s\n",errno,strerror(errno));
    return 254;  
}


wait(pid);

...

pid_t wait_status = wait(&pid);

这篇关于使用execv(C语言)从linux命令提示符运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆