- 论坛徽章:
- 0
|
pzpopen:
返回的是文件描述符
#include unistd.h>
#include stdio.h>
#include sys/types.h>
int pzpopen(char *proc, char *mode) {
int pipe_d[2];
pid_t pid;
if(pipe(pipe_d) != 0) {
fprintf(stderr, "pipe failed!\n");
return -1;
}
if(*mode == 'r' && *(mode + 1) == '\0'){
pid = fork();
switch(pid) {
case -1:
fprintf(stderr, "fork failed.\n");
return -1;
case 0:
dup2(pipe_d[1], 1);
close(pipe_d[1]);
close(pipe_d[0]);
execl(proc, proc, NULL);
fprintf(stderr, "execl failed.\n");
return -1;
}
close(pipe_d[1]);
return pipe_d[0];
}else if(*mode == 'w' && *(mode + 1) == '\0') {
pid = fork();
switch(pid) {
case -1:
fprintf(stderr, "fork failed.\n");
return -1;
case 0:
dup2(pipe_d[0], 0);
close(pipe_d[0]);
close(pipe_d[1]);
execl(proc, proc, NULL);
fprintf(stderr, "execl failed.\n");
return -1;
}
close(pipe_d[0]);
return pipe_d[1];
}
fprintf(stderr, "Unknown mode %s!\n", mode);
return -1;
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/77943/showart_1987956.html |
|