[英]How to properly run a shell script in C++
我正在尝试在我的.cpp文件中执行此操作:
system("/home/user/workspace/script.sh");
我只想打开它,让它在外壳上运行,然后就不用管它了。 到目前为止,我的解决方案只是这样做:
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()
函数导致使用当前外壳运行单独的进程(这是解释字符串参数的过程),并且该进程的行为与您手动从外壳运行它的行为完全相同(也就是说,它将吐出其stdout和stderr流照常)。 您可以做两件事:
system()
运行时将输出重定向到某处(如注释所提示) fork()
,然后使用execl()
“使进程将自身切换为命令”。 在fork()
和execl()
您可以close()
不需要的流(1 = stdout,2 = stderr),如果这在尝试写入已关闭文件时导致运行辅助进程时出现问题,则可以dup()
给他们一个新的open()
ed描述符到“ / dev / null”文件 实际上,第二个解决方案与最终结果中的第一个解决方案相同-不同之处在于,第二个解决方案不使用Shell来执行您的过程,但是更为复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.