Inherit file descriptors from parent process?

J

James Thornton

How do you inherit the stdin and stdout file descriptors from a parent
process? Specifically, the following function "run_filters" forks and
calls several perl scripts via execvp.

One of the perl scripts needs to execute a virus scanner on the file
pointed to by the parent file descriptor, modifying the file as
needed. The virus scanner will be invoked via a system call where
$file is the file name associated with the file parent file
descriptor:

system $virus_binary $file;

// C program that forks and executes several
// Perl scripts via execvp
int run_filters(command* first, int fdin)
{
command* c;

for(c = first; c; c = c->next) {
pid_t pid;
int status;
int fdout;

fdout = mktmpfile();
if(fdout == -1)
return -QQ_WRITE_ERROR;
pid = fork();
if(pid == -1)
return -QQ_OOM;
if(pid == 0) {
if(close(0) == -1 ||
dup2(fdin, 0) != 0 ||
close(1) == -1 ||
dup2(fdout, 1) != 1)
exit(QQ_WRITE_ERROR);
execvp(c->argv[0], c->argv);
exit(QQ_INTERNAL);
}
if(waitpid(pid, &status, WUNTRACED) == -1)
return -QQ_INTERNAL;
if(!WIFEXITED(status))
return -QQ_INTERNAL;
if(WEXITSTATUS(status))
return -WEXITSTATUS(status);
close(fdin);
if(lseek(fdout, 0, SEEK_SET) != 0)
return -QQ_WRITE_ERROR;
fdin = fdout;
}
return fdin;
}
 
M

Malcolm Dew-Jones

James Thornton ([email protected]) wrote:
: How do you inherit the stdin and stdout file descriptors from a parent
: process? Specifically, the following function "run_filters" forks and
: calls several perl scripts via execvp.

Normally you inherit them buy doing nothing. The command that is spawned
will read from the same stdin and write to the same stdout. (If several
programs are all ready the same stdin at the same time then they each get
a turn at reading.)

For example, this runs perl, then spawns out to the cat command which
echoes its stdin to stdout, and then when it return to perl then perl
prints to stdout.

C:> perl -e "print 'this is perl'; system('cat'); print 'back to perl'"

The output I get (includes some things I typed)

this is perl

hello
hello
back to perl

(My example uses system(), but all system does is fork and exec, so its
really no different.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top