在c ++ Linux中调用"system"时隐藏sh:-c错误消息

sfa*_*ost 2 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
Run Code Online (Sandbox Code Playgroud)

如何抑制这些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;
}
Run Code Online (Sandbox Code Playgroud)

你能帮助我吗?

who*_*oan 5

认为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;
}
Run Code Online (Sandbox Code Playgroud)

要静默抑制对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;
}
Run Code Online (Sandbox Code Playgroud)

请记住检查函数调用的返回值.