在 linux 上执行,从参数执行

execve on linux, execute from arguments

我需要创建一个程序,允许用户使用 linux 中的 execve 执行作为参数传递的命令。我不确定 execve 命令的语法。我写了这个程序,但它不能使用多个参数,我不明白为什么。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
int main(int argc, char **argv)
{
int status;
pid_t pid;
if((pid = fork())>0)
{
    ///Father process
    wait(&status);
    printf("Process terminated with status = %d\n",status);
}
else
{
    ///son process
    int i;
    char param[100];

    printf("I'm the son woth PID= %d\n",getpid());
    printf("%s\n",argv[0]);
    printf("%s\n",argv[1]);
    printf("%s\n",argv[2]);
    strcpy(param,"/bin/");
    strcat(param,argv[1]);  

    execve(param,argv,NULL);
    exit(-1);
}


return 0;
}

无法使用此代码的命令是

cp file1.txt file2.txt

有人可以帮助我吗?

此版本更正:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
int main(int argc, char **argv)
{
int status;
pid_t pid;
if((pid = fork())>0)
{
    ///Father process
    wait(&status);
    printf("Process terminated with status = %d\n",status);
}
else
{
    ///son process
    int i;
    char program[100];

    printf("I'm the son woth PID= %d\n",getpid());
    strcpy(program,argv[1]);

    printf("Program: %s\n", program);

    execve(program, argv+1, NULL);
    exit(0);
}


return 0;
}

示例:

$ ./a.out /bin/cp a.txt b.txt
I'm the son woth PID= 1590
Program: /bin/cp
/bin/cp
a.txt
b.txt
Process terminated with status = 0

示例 2:

./a.out /bin/ls
I'm the son woth PID= 3021
Program: /bin/ls
/bin/ls
a.c a.out
Process terminated with status = 0

我添加了 #include <unistd.h> 因为我需要它。

我建议你做更多的事情printf以便理解和解决问题。

编辑 正如@jonathan-leffler 所说,您可以使用 execvp 来执行使用 PATH 的程序:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
int main(int argc, char **argv)
{
int status;
pid_t pid;
if((pid = fork())>0)
{
    ///Father process
    wait(&status);
    printf("Process terminated with status = %d\n",status);
}
else
{
    ///son process
    int i;
    char program[100];

    printf("I'm the son woth PID= %d\n",getpid());
    strcpy(program,argv[1]);

    printf("Program: %s\n", program);

    execvp(program, argv+1);
    exit(0);
}


return 0;
}

示例:

▶ ./a.out ls
I'm the son woth PID= 5056
Program: ls
a.c a.out
Process terminated with status = 0