gpt4 book ai didi

c - 将 Fork 用于命令行参数

转载 作者:太空宇宙 更新时间:2023-11-04 08:17:00 24 4
gpt4 key购买 nike

我正在尝试执行命令“ls -l”,但我不确定如何处理它。

这是我试过的:

int main(void) {
char * input;
char * args[2];
char buff[100];

input = malloc(sizeof(buff));

while(fgets(input,sizeof(input),stdin) != NULL) {

printf("Enter a command\n");

if(strcmp(input,"ls -l\n") ==0) {
pid_t childPid;

childPid = fork();

if(childPid == 0) {
args[0] = "/bin/ls -l";
args[1] = NULL;

execv(args[0],args);
}

}

}

free(input);
}

但是,该命令在这里似乎不起作用。如果我只是简单地使用“ls”但我想使用“ls -l”它会起作用我是否必须传递另一个参数才能让它起作用?

最佳答案

当您调用任何 exec() 变体时,您必须分别传递每个参数,如

args[0] = "/bin/ls";
args[1] = "-l";
args[2] = NULL;

关于c - 将 Fork 用于命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35261054/

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