c++ - 隐藏 sh : -c error messages when calling “system” in c++ Linux

标签 c++ linux bash

我正在使用系统来执行带有参数的命令。我不想使用 exec/fork。 当我的命令中有不匹配的引号时,会出现此错误:

sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file

如何抑制这些 shell 的 错误消息?我尝试在无效命令的末尾添加 >/dev/null 2>&1 但它不会抑制 shell 错误消息。对于背景,我正在运行用户提供的命令,这些命令可能有效也可能无效。我无法提前知道它们是否有效,但无论如何我都想抑制错误消息。

这是生成我试图抑制的错误类型的代码示例:

int main()
{
   // This command is meant to be invalid as I'm trying to suppress the shell syntax error message
   system("date ' >/dev/null 2>&1");
   return 0;
}

你能帮帮我吗?

最佳答案

认为 system 派生了一个进程,然后执行您提供的命令。新进程从其父进程继承描述符,并且该新进程写入其标准错误。

因此,此代码片段可能会执行您想要的操作:

#include <stdlib.h>
#include <unistd.h>

int main()
{
    int duperr;
    duperr = dup(2);
    close(2); /* close stderr so the new process can't output the error */
    system("date '");
    dup2(duperr, 2);
    close(duperr);
    /* here you can use stderr again */
    write(2, "hello world\n", 12);
    return 0;
}

要静默抑制对 stderr 的写入,您可以将错误输出到 /dev/null:

#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main(void) {
    int devnull_fd, duperr_fd;
    /* get a descriptor to /dev/null (devnull_fd) */
    devnull_fd = open("/dev/null", O_WRONLY | O_APPEND);
    /* save a descriptor "pointing" to the actual stderr (duperr_fd) */
    duperr_fd = dup(STDERR_FILENO);
    /* now STDERR_FILENO "points" to "/dev/null" */
    dup2(devnull_fd, STDERR_FILENO); 

    system("date '");
    /* restore stderr */
    dup2(duperr_fd, STDERR_FILENO);
    close(duperr_fd);
    close(devnull_fd);
    /* here you can use stderr again */
    write(STDERR_FILENO, "hello world\n", 12);
    return 0;
}

记得检查函数调用的返回值。

关于c++ - 隐藏 sh : -c error messages when calling “system” in c++ Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27709346/

相关文章:

linux - 在 bash 中使用 expect inside ssh 执行 sudo

python - 使用 Expect 在远程机器上运行本地 Python 脚本

c++ - 解码 H264/RTSP 流后未设置 PTS

linux - 执行时拦截错误

python - 如何在线程后继续代码?对这段代码的流程感到困惑

python - 无法在 Linux Ubuntu 上安装 mysqlclient-python

regex - 查找 unicode 字符串的十六进制代码

c++ - 并发写入 vector<bool>

c++ - 关闭父级以调用隐藏或显式关闭时消息框未关闭

c++ - g++ 给 "unresolved overloaded function type"模板参数