gpt4 book ai didi

c - 在 shell 程序中调用 system() 是不好的做法吗?

转载 作者:太空宇宙 更新时间:2023-11-04 06:20:12 25 4
gpt4 key购买 nike

我正在编写自定义 shell command language interpreter我看到其他 shell 使用对 system() 的调用执行管道或高级 shell 程序。使用 execfork 执行管道而不是调用 system() 不是更好吗?例如,如果它是救援 shell 或其他一些情况,那么您可能无法访问资源 system()

/* With the standard output plumbing sorted, execute Nth command */
static void exec_nth_command(int ncmds, char ***cmds) {
assert(ncmds >= 1);
if (ncmds > 1) {
pid_t pid;
Pipe input;
if (pipe(input) != 0)
err_sysexit("Failed to create pipe");
if ((pid = fork()) < 0)
err_sysexit("Failed to fork");
if (pid == 0) {
/* Child */
exec_pipe_command(ncmds - 1, cmds, input);
}
/* Fix standard input to read end of pipe */
dup2(input[0], 0);
close(input[0]);
close(input[1]);
}
execvp(cmds[ncmds - 1][0], cmds[ncmds - 1]);
err_sysexit("Failed to exec %s", cmds[ncmds - 1][0]);
/*NOTREACHED*/
}

/* Given pipe, plumb it to standard output, then execute Nth command */
static void exec_pipe_command(int ncmds, char ***cmds, Pipe output) {
assert(ncmds >= 1);
/* Fix stdout to write end of pipe */
dup2(output[1], 1);
close(output[0]);
close(output[1]);
exec_nth_command(ncmds, cmds);
}

/* Execute the N commands in the pipeline */
void exec_pipeline(int ncmds, char ***cmds) {
assert(ncmds >= 1);
pid_t pid;
if ((pid = fork()) < 0)
err_syswarn("Failed to fork");
if (pid != 0)
return;
exec_nth_command(ncmds, cmds);
}

正如您从上面的代码中看到的,我从不在我的 shell 中调用 system() 但这是有充分理由的吗?

最佳答案

由于您正在实现一个新的 shell,因此在内部使用 system(3) 会显得很奇怪,因为 system(3) 使用系统默认 shell,这几乎可以肯定与您正在实现的 shell 不同的 shell 。

此外,system(3) 确实使某些类型的错误处理变得更加困难——您无法完全了解启动子进程后发生的情况。

关于c - 在 shell 程序中调用 system() 是不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36818513/

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