2008年7月16日 星期三

IPC

估唔到, 畢左業咁耐都要找返d 書出來. 因為最近收到一個 support call, 同事想o係佢個程式裡面呼叫另一個程式, 然後向該程式詢問數次, 並用其回覆進行運算. 而被呼叫果個程式係起動得好慢同時會佔用很多資源, 並且會以"亙動模式"運行. 同事唔希望每一次詢問都重新呼叫一次, 因為咁樣做會好慢, 唯有做 IPC 啦.
咁個 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);
}
}
}

沒有留言: