c++ system(): how to make it silent

How do I silence system()? So that it does not output anything to the terminal. Is it possible to redirect the output to a file using fstream instead of stdio.h?

 2
Author: avp, 2015-04-20

2 answers

For example, to form a command with output redirection to /dev/null, in *nix

cmd параметры 1&>2 /dev/null

Update

If you want (checked in Linux only) to really carefully redirect the output in your program before system, and then go back to the original one, you will have to write something like this:

#ifdef __cplusplus
#include <iostream>
using namespace std;
#endif

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

int hide_fileno (FILE *f, const char *dst)
{
  fflush(f);
  int fd, 
    efd = fileno(f), 
    save = dup(efd), 
    olderr = errno;
  if (dup2(fd = open(dst, O_WRONLY | O_CREAT | O_TRUNC, 0664), efd) == -1) {
    olderr = errno;
    close(save);
    save = -1;
  }
  close(fd);
  errno = olderr;
  return save;
}

int rest_fileno (FILE *f, int savefd)
{
  int drc = dup2(savefd, fileno(f));
  if (drc != -1)
    close(savefd);
  return drc;
}

int 
main (int ac, char *av[])
{
#ifdef __cplusplus
  cout << "Goooo ";
  cerr << "main: " << strerror(errno) << '\n';
#else
  printf("goo... ");
  perror("main");
#endif

  int saveout = hide_fileno(stdout, "/dev/null"), 
    saveerr = hide_fileno(stderr, "/dev/null");


  int rc = system("grep xaxa c1.c /");

  rest_fileno(stdout, saveout);
  rest_fileno(stderr, saveerr);

#ifdef __cplusplus
  cerr << "system: " << strerror(errno) << '\n';
  cout << "rc = " << rc << '\n';
#else
  perror("system");
  printf("rc = %d\n", rc);
#endif
}

The point here is that the freopen () suggested in the comment to @Pavel Mayorov's answer is a "one-way path".

 4
Author: avp, 2015-04-20 18:14:24

Another option is to close stdin, stdout, and stderr.

If you need to output something there yourself, you must first clone the file descriptors.

 3
Author: Pavel Mayorov, 2015-04-20 14:10:42