1

I am trying to create my own "shell" program.

Basically you would run it and give it a command (ifconfig, ls, etc) and it would run it via popen and then return the output.

The issue is I cannot get STDERR.

I have read that I can redirect stderr to stdout by using 2>&1 however I prefer to not do that since this will be ran across all sorts of different linux versions and shells.

Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74
xf900
  • 35
  • 4
  • 1
    Does this answer your question? [Redirect standard error to a string in C](https://stackoverflow.com/questions/14715493/redirect-standard-error-to-a-string-in-c) – mas Mar 29 '22 at 13:19
  • I am looking over it and it seems like it is close but I need to be able to capture the output from popen. I haven't been able to get fgets to get the stderr from popen or even get popen to output stderr. – xf900 Mar 29 '22 at 13:30
  • 2
    If you want complete control over input & output, you can't use `popen()`, because that isn't what it does. Just use `pipe()` and `fork()` directly to manage stdin, stdout & stderr from the child process. – Useless Mar 29 '22 at 13:47
  • I prefer to not use fork. I don't see why I should have to duplicate my entire process just to run a simple command. I am sure fork has its uses but it doesn't apply to this. – xf900 Mar 29 '22 at 13:49
  • 2
    You have to use `fork()` directly or indirectly because it is the only way to create new processes. (Well, there is `posix_spawn()` to look at too.) – Jonathan Leffler Mar 29 '22 at 13:56
  • 1
    "I don't see why I should have to duplicate my entire process just to run a simple command." Because it's an inherent design feature of Unix, that's why. They decided to make "create new process" and "run new program" be two separate operations. So if "create new process" doesn't run a new program, then necessarily the new process must be running the same program as the old one. Hence `fork`. In order to run a "simple command" in a new process, you do have to first duplicate the current one. Every other method of running a new command, including `popen`, already does this internally. – Nate Eldredge Mar 29 '22 at 15:23

0 Answers0