本文介绍了C-不使用popen的管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我该如何转换呢?
FILE *f;
char in_buffer[80];
f=popen("command","r");
fgets(in_buffer,sizeof(in_buffer),f)
不使用popen()
,而仅使用pipe()
或其他指令?
without using popen()
, but only pipe()
or other instruction?
推荐答案
这是我的简单实现,带有注释,说明正在做的事情.
Here's my simple implementation, with comments explaining what's being done.
#include <unistd.h>
#include <stdio.h>
FILE *
my_popen (const char *cmd)
{
int fd[2];
int read_fd, write_fd;
int pid;
/* First, create a pipe and a pair of file descriptors for its both ends */
pipe(fd);
read_fd = fd[0];
write_fd = fd[1];
/* Now fork in order to create process from we'll read from */
pid = fork();
if (pid == 0) {
/* Child process */
/* Close "read" endpoint - child will only use write end */
close(read_fd);
/* Now "bind" fd 1 (standard output) to our "write" end of pipe */
dup2(write_fd,1);
/* Close original descriptor we got from pipe() */
close(write_fd);
/* Execute command via shell - this will replace current process */
execl("/bin/sh", "sh", "-c", cmd, NULL);
/* Don't let compiler be angry with us */
return NULL;
} else {
/* Parent */
/* Close "write" end, not needed in this process */
close(write_fd);
/* Parent process is simpler - just create FILE* from file descriptor,
for compatibility with popen() */
return fdopen(read_fd, "r");
}
}
int main ()
{
FILE *p = my_popen ("ls -l");
char buffer[1024];
while (fgets(buffer, 1024, p)) {
printf (" => %s", buffer);
}
fclose(p);
}
注意:
- 第三代码仅支持
popen
的"r"
模式.实施其他模式(即"w"
模式)留给读者练习. - 此示例中使用的系统功能可能会失败-错误处理留给读者练习.
-
pclose
的实现留给读者练习-参见close
,waiptid
和fclose
.
- Thir code supports only
"r"
mode ofpopen
. Implementing other modes, namely"w"
mode is left as an exercise for the reader. - System functions used in this example may fail - error handling is left as an exercise for the reader.
- Implementation of
pclose
is left as an exercise for the reader - seeclose
,waiptid
, andfclose
.
如果您要查看实际的影响,则可以查看 OSX , GNU glibc 和 OpenSolaris ,等等.
If you want to look at real impementations, you can look into sources of OSX, GNU glibc and OpenSolaris, among others.
希望这会有所帮助!
这篇关于C-不使用popen的管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!