c - 使用 execv(C 语言)从 linux 命令提示符运行命令

标签 c unix argv execv

到目前为止,我唯一感到困惑的部分是如何将第一个参数设置为当前工作目录的 execv。我已经尝试了两个“。”和“~”,它们都没有在屏幕上执行任何操作; “/”也一样。和“/~”。我对如何让 execv 运行这样的东西感到困惑:

$ ./prog ls -t -al

并让它在当前目录或与文件所在的同一目录(根据使用者的不同而有所不同)中执行程序执行后的命令(存储在 argv 中)

我的代码:

#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 设置中查找命令。

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

关于c - 使用 execv(C 语言)从 linux 命令提示符运行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12575826/

相关文章:

bash - 在 bash 中解析电子邮件中的发件人姓名

c - 查找不可打印的字符并在 C 中打印出它们的十六进制形式

linux - vim 向上或向下移动选定代码块

c - 变量在读取文件的循环中不递增

bash - 将 'command with a pipe' 作为 bash 函数参数传递

c - 如何在 C 中排除从命令提示符 argc argv 传递的参数?

汇编:__p___argv 的返回值

c - execvp 和参数类型 - ansi c

c - 为什么指针值被用作 .而不是 -> 在此

python - 如何将复数从 python numpy 传递到 c(目前正在尝试使用 SWIG)