gpt4 book ai didi

c - 在 C 程序中执行带有选项的命令

转载 作者:行者123 更新时间:2023-11-30 16:02:09 25 4
gpt4 key购买 nike

我正在尝试在 C 程序中执行带参数的命令。例如,当用户使用以下命令执行我的程序时:“./a.out ls -la”

程序应使用 la 选项执行 ls。

但我不知道该怎么做。

我的程序使用fork。

我尝试这样:

pid = fork();

if(pid == 0){

execvp(argv[1], &argv[2]);

}else{

wait(NULL);

}

但是它不起作用。

我想将数组作为 execvp 的第二个参数传递,并在命令中传递参数,但我对指针有点困惑(更多的是指针的指针:s)。

我知道这不起作用,因为参数中的破折号,但即使我不使用破折号,程序也只会启动“ls”而不处理“la”选项。

如果有人可以帮助我,我会很高兴知道该怎么做。

谢谢。

最佳答案

系统

引用维基百科:

In the C standard library, system is a function used to execute subprocesses and commands. It is defined in stdlib.h header. It differs from the exec/spawn family of functions in that instead of passing arguments to an executed object, a single string is passed to the system shell, typically the POSIX shell, /bin/sh -c.

http://en.wikipedia.org/wiki/System_(C_standard_library )

关于c - 在 C 程序中执行带有选项的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5618416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com