Redirecting Standard In and Out in C (Linux)

I'm trying to redirect both the standard in and out of a process that my process is going to create, so I can communicate bidirectionally with this process.

Basically, I'm trying to accomplish Python's popen2() in C.

I haven't been able to find anything on this, as everyone seems to be using fork() in their examples, which is convenient because you can create pipes, fork, and then dup() in the child to change your stdin and stdout, however, in my case I'm not forking, I'm actually executing a shell command and I want to be able to communicate with it.

Upvotes: 1

Views: 460

Answers (3)

Ahmed Masud
Ahmed Masud

Reputation: 22372

popen2 of Python does fork a shell process and is implemented using popen(3).

popen(3) is part of the POSIX standard and is supported under Linux. However note that popen can only create a unidirectional communication (either read-only or write-only). popen(3) is a wrapper around pipe(2) system call.

If you want to do both Input and Output on the same descriptor then you are entering the realm of sockets. You can implement a UNIX sockets (local communications) see unix(7) for details — there are appropriate C examples in the man pages as well so I won't repost here.

Upvotes: 0

Some unixes make this easy by having popen (3) support bi-direction pipes (most BSDs including Mac OS; don't know about linux off the top of my head), but this is not required and other only support one direction with popen. For those you have to establish two uni-directional pipes yourself using pipe (2), fork and exec.

Upvotes: 0

thiton
thiton

Reputation: 36049

You cannot execute a shell command without forking the process. It is done internally by functions like system, and you should just do it explicitely to capture stdin/stdout. After you are done forking and setting up stdin/stdout via dup2 in the pipes you have created before, call exec with your shell, the "-c" argument and the shell command you want to fork.

Upvotes: 1

Related Questions