如何在 C++ 中正确 运行 一个 shell 脚本

How to properly run a shell script in C++

我正尝试在我的 .cpp 文件中执行此操作:

system("/home/user/workspace/script.sh");

我只想打开它,在其 shell 上获取它 运行 然后忘记它。到目前为止,我的解决方案就是这样做:

pid_t pid = fork();
if (pid == 0) {
    system("/home/user/workspace/script.sh");
}

并且有效。问题是我不确定这样做是否正确,但即使正确,我也会收到一些我不想在输出中看到的警告:

(gnome-terminal:8105): GLib-GIO-CRITICAL **: g_settings_get: the format string may not contain '&' (key 'monospace-font-name' from schema 'org.gnome.desktop.interface'). This call will probably stop working with a future version of glib.

(gnome-terminal:8105): Vte-2.90-WARNING **: No se pueden convertir caracteres de UTF-8 a actual.

(gnome-terminal:8105): Vte-2.90-WARNING **: No se pueden convertir caracteres de UTF-8 a actual.

(gnome-terminal:8105): Vte-2.90-WARNING **: No se pueden convertir caracteres de UTF-8 a actual.
Unhandled value type TerminalEncoding of pspec encoding

有什么建议吗?非常感谢。

system() 函数导致 运行 使用当前 shell 的单独进程(这就是解释字符串参数的原因),并且此进程的行为与 运行 它从 shell 手动(也就是说,它会像往常一样吐出它的 stdout 和 stderr 流)。你可以做两件事:

  • 当 运行 来自 system() 时将输出重定向到某处(如评论中所提示)
  • 使用子进程通道重定向 - fork(),然后 "make the process switch itself into a command" 使用 execl()。在 fork()execl() 之间,您可以 close() 不需要的流(1 = stdout,2 = stderr),如果这在 运行 辅助进程尝试写入时引起问题到一个关闭的文件,你可以 dup() 给他们一个新的 open()-ed 描述符到一个“/dev/null”文件

其实第二种解决方案和第一种解决方案的最终结果是一样的——不同的是第二种解决方案不涉及shell执行你的过程,但它更复杂。