Next Generation Emulation banner
1 - 10 of 10 Posts

·
Registered
Joined
·
182 Posts
Doesn't system block until the command in question is finished executing? That being the case, the caller won't even resume until the child process is finished and any STDIO streams associated with it are closed. What's the reason you don't want to use popen or fork?
 

·
ಠ_ಠ
Joined
·
2,364 Posts
Discussion Starter · #3 ·
Doesn't system block until the command in question is finished executing? That being the case, the caller won't even resume until the child process is finished and any STDIO streams associated with it are closed.
I know, but I want to know if there is any way around it. :X

What's the reason you don't want to use popen or fork?
It's the requirement from an assignment that I can't use those. The only command I can use are system(...), close(...), pipe(...), dup(...), dup2(...), read(...) and write(...).
 

·
ಠ_ಠ
Joined
·
2,364 Posts
Discussion Starter · #8 ·
Here is a sample code that uses system(...), close(...), pipe(...), dup(...), dup2(...), read(...) and write(...).

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

// Pipes the output of one program and use it as an input of another

main() {
  int fd[2];
  int std_in, std_out;
  char buf[6];

  if (pipe(fd) < 0)
    return -1;

  // stores the fd for stdin and stdout, so they can be restored later
  std_in = dup(STDIN_FILENO);
  std_out = dup(STDOUT_FILENO);

  dup2(fd[1], STDOUT_FILENO);
  system("echo hello world");
  close(fd[1]);
  dup2(std_out, STDOUT_FILENO);

  dup2(fd[0], STDIN_FILENO);
  read(fd[0], buf, 5);
  write(1, buf, 5);
  close(fd[0]);
  dup2(std_in, STDIN_FILENO);
}
 
1 - 10 of 10 Posts
This is an older thread, you may not receive a response, and could be reviving an old thread. Please consider creating a new thread.
Top