您可以通过在 fork 之后但之前将 stdout 和 stderr 重定向到 /dev/null 来隐藏输出execve()。这个想法是打开/dev/null,然后使用dup2()(这也将首先关闭原始文件)制作获得的文件描述符的stdout和stderr副本。这几乎与重定向到管道相同。
一个例子(不完整的程序,跳过大多数错误检查):
#include <unistd.h>
#include <fcntl.h>
...
int pid = fork();
if (pid == -1) {
/* fork error */
exit(1);
} else if (pid == 0) {
/* child process */
/* open /dev/null for writing */
int fd = open("/dev/null", O_WRONLY);
dup2(fd, 1); /* make stdout a copy of fd (> /dev/null) */
dup2(fd, 2); /* ...and same with stderr */
close(fd); /* close fd */
/* stdout and stderr now write to /dev/null */
/* ready to call exec */
execve(cmd, args, env);
exit(1);
} else {
/* parent process */
...
Run Code Online (Sandbox Code Playgroud)