[Fwd: Re: dangerous stuff popen2()]
Kim Holburn
kim.holburn at anu.edu.au
Tue Oct 16 10:08:43 EST 2001
Here's one I wrote/adapted ages ago. Two files ppipe.h and ppipe.c
ppipe.h:
------------------------------------------------
/* @(#)ppipe.h 1.2 97/09/19 (12:20:14) */
int ppopen(FILE **IN, FILE **OUT, char *shcmd, int *pid);
int ppclose(int pid);
/*
create pipe that my program can output to and input from
Used in this order :
FILE *IN, *OUT;
int pid;
if (ppopen (&IN, &OUT, "shell command", &pid)!=0) don't do it;
fprintf (OUT, "things");
fclose (OUT);
fgets (IN etc
fclose (IN);
ppclose(pid)
*/
------------------------------------------------
ppipe.c
------------------------------------------------
/* ppipe.c */
/* @(#)ppipe.c 1.1 97/09/19 (12:15:38) */
#include <stdio.h>
#include <unistd.h>
/*
parent child
------ -----
pfd1[1] ---> pfd1[0]
close pfd1[0] close pfd1[1]
|
v
system
|
v
pfd2[0] <--- pfd2[1]
close pfd2[1] close pfd2[0]
*/
int ppopen(FILE **IN, FILE **OUT, char *shcmd, int *pid)
{
static int pfd1[2]; /* pipe, from parent to child */
static int pfd2[2]; /* pipe, from child to parent */
/*
* create a pipe, generally speak, a pipe is a half-duplex
* communication channel (except SVR4)
*/
if (pipe(pfd1) < 0) {
perror("pipe one creation");
return 1;
}
if (pipe(pfd2) < 0) {
perror("pipe two creation");
return 2;
}
/*
* fork a child process
*/
if ((*pid=fork()) <0 ) {
perror("fork child");
return 3;
}
/*
* the shell command get executed by the child process
*/
if (*pid == 0) {
/*
* redirect the standard input and output
*/
dup2(pfd1[0], 0);
dup2(pfd2[1], 1);
close(pfd1[1]);
close(pfd2[0]);
/*
* execute the shell command, the output goes to the pipe
*/
system(shcmd);
exit(0);
} /* child process */
/*
* in the parent process, pfd1[1] and pfd2[0] is useless
*/
close(pfd1[0]);
close(pfd2[1]);
/*
* pipe data into the child process
*/
*OUT=fdopen (pfd1[1], "w");
/*
* read data from the child process
*/
*IN=fdopen (pfd2[0], "r");
return 0;
}
int ppclose (int pid)
{
int status; /* exit status of child process */
waitpid(pid, &status, 0);
return(status);
}
--------------------------------------------------------
--
--
Kim Holburn Network Consultant P/F: +61 2 61258620 M: +61 0417820641
Email: kim.holburn at anu.edu.au - PGP Public Key on request
Life is complex - It has real and imaginary parts.
Andrea Leistra (rec.arts.sf.written.Robert-jordan)
More information about the linux
mailing list