gpt4 book ai didi

C - 不使用 popen 的管道

转载 作者:太空狗 更新时间:2023-10-29 17:19:43 26 4
gpt4 key购买 nike

我怎样才能改变这个:

FILE *f;
char in_buffer[80];
f=popen("command","r");
fgets(in_buffer,sizeof(in_buffer),f)

不使用popen(),而只使用pipe()或其他指令?

最佳答案

这是我的简单实现,并附有说明所做操作的注释。

#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);
}

注意事项:

  1. 他们的代码只支持 popen"r" 模式。实现其他模式,即 "w" 模式留给读者作为练习。
  2. 此示例中使用的系统函数可能会失败 - 错误处理留给读者作为练习。
  3. pclose 的实现留给读者作为练习 - 请参阅 closewaiptidfclose .

如果您想查看真正的实现,可以查看 OSX 的来源, GNU glibcOpenSolaris ,等等。

希望这对您有所帮助!

关于C - 不使用 popen 的管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19667243/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com