运行 linux 命令使用 execlp 并在 c 中将多个参数作为字符串

run linux command using execlp with more than one argument as string in c

我正在尝试 运行 ls 在 C 中使用带有多个参数的系统调用,例如 -l -a。参数及其数量根据用户输入而变化。输入连接“-l”+“-a”==“-l -a”。我使用的代码是:

execlp("ls","ls",arguments,NULL) //arguments = "-l -a"

用户输入来自终端:

-l
-a

如果你想执行多个参数,那么你应该使用 execvp() 而不是 execlp

#include<stdio.h>
#include <unistd.h>
int main(int argc,char *argv[])
{

        execvp(argv[1],argv+1);// argv+1 means whatever arguments after argv[1] it will take & executes it 
        return 0;
}

例如你的输入

xyz@xyz-PC:~$ ./a.out ps -el

希望对您有所帮助。