咁個 call 就送左過來, 我便用 pipe() 寫了一個好簡單 IPC o既例子比佢, 呼叫 ed, 行句指令再叫佢結束. 其實, 而家學校仲有冇教 IPC o既呢?
p.c
#include <stdio.h>
#include <sys/types.h>
main()
{
pid_t pid;
int rval;
int pta[2]; // parent stdout, child stdin
int ptb[2]; // parent stdin, child stderr
char pres[250];
// Create pipes
if ( pipe(pta) )
{
fprintf(stderr,"create pipe A error!\n");
exit(1);
}
if ( pipe(ptb) )
{
fprintf(stderr,"create pipe B error!\n");
exit(1);
}
// fork process
if ( (pid=fork()) == -1 )
{
fprintf(stderr,"fork error\n");
exit(1);
}
if ( pid )
{
// parent side
dup2(pta[1],1); // replace stdout with pipe
dup2(ptb[0],0); // replace stdin with pipe
setvbuf(stdout,(char*)NULL,_IONBF,0); // set non-buffered output on stdout
sleep(2);
printf("l\n");
fgets(pres,sizeof(pres),stdin);
fprintf(stderr,"output of child from pipe : %s\n",pres);
if ( strncmp(pres,"?",1) == 0 )
{
printf("q\n");
}
else
{
fprintf(stderr,"Error : Unknown output from child.\n");
exit(1);
}
wait(&rval); // wait for child process
fprintf(stderr,"child process exited -- %d\n",rval);
}
else
{
// child side
dup2(pta[0],0); // replace stdin with pipe
dup2(ptb[1],2); // replace stderr with pipe, as the output of our command in ed is out to stderr
// use dup2(ptb[1],1); if replace stdout with pipe
// call external porgram ed
if ( execl("/bin/ed","ed",NULL) == -1 )
{
fprintf(stderr,"call external program error");
exit(1);
}
}
}
沒有留言:
張貼留言