Replacing and then opening stdin / stdout by ssh

I am working on a system that communicates with child processes using pipes for stdin and stdout. To facilitate this connection, child processes use the api library, and I need to write unit tests for the library. The only way to figure out how to properly test these functions is to replace stdin / stdout with pipes so that tests can pretend to be the parent system when calling the functions.

/* replace stdin and stdout with pipes */
void setup(void) {
  pipe(in_sub);
  pipe(out_sub);

  dup2(out_sub[1], fileno(stdout));
  dup2( in_sub[0],  fileno(stdin));
  read_from = fdopen(out_sub[0], "rb");
  write_to  = fdopen( in_sub[1], "wb");

  stdout_t = fopen("/dev/tty", "wb");
  stdin_t  = fopen("/dev/tty", "rb");
}

/* reopen stdin and stdout for future test suites */
void teardown(void) {
  fclose(read_from);
  fclose(write_to);

  stdout = stdout_t;
  stdin  = stdin_t;

  close(in_sub[0]);
  close(in_sub[1]);
  close(out_sub[0]);
  close(out_sub[1]);
}

stdin stdout temps fdopen() ( , FILE *), , . . ssh. , - stdout , .

, dup2, stdin stdout , stdin stdout, ssh?

+5
1

stdin, stdout - FILE *, (), fd, 0 ( 1). , dup2, 0 1 . , , dup2, ;

void setup(void) {
  int dupin, dupout;

  dupin = dup(0);  // Create an extra fd to stdin
  dupout = dup(1);  // create an extra fd to stdout

  pipe(in_sub);
  pipe(out_sub);

  dup2(out_sub[1], fileno(stdout));
  dup2( in_sub[0],  fileno(stdin));
  read_from = fdopen(out_sub[0], "rb");
  write_to  = fdopen( in_sub[1], "wb");

  stdout_t = fdopen(dupout, "wb");
  stdin_t  = fdopen(dupin, "rb");
}
+3

All Articles