gpt4 book ai didi

c++ - 我们有类似 C 或 C++ 中的 perl 的 IPC::Open3 的东西吗

转载 作者:行者123 更新时间:2023-11-30 16:36:41 26 4
gpt4 key购买 nike

我使用perl的open3来运行命令,自定义命令的行为就像一个shell,它接受输入并显示输出并等待另一个输入直到给出退出

现在我必须使用相同的命令并用 C 语言编写它,我们是否有类似于 C 或 C++ 中的 IPC::Open3 的东西?

最佳答案

popen()支持单向通信。如果您想要双向数据交换,则需要 2 个管道。 Jeff Epler想出了以下双向 popen2.c实现:

#include <sys/types.h>
#include <unistd.h>

struct popen2 {
pid_t child_pid;
int from_child, to_child;
};

int popen2(const char *cmdline, struct popen2 *childinfo) {
pid_t p;
int pipe_stdin[2], pipe_stdout[2];

if(pipe(pipe_stdin)) return -1;
if(pipe(pipe_stdout)) return -1;

printf("pipe_stdin[0] = %d, pipe_stdin[1] = %d\n", pipe_stdin[0], pipe_stdin[1]);
printf("pipe_stdout[0] = %d, pipe_stdout[1] = %d\n", pipe_stdout[0], pipe_stdout[1]);

p = fork();
if(p < 0) return p; /* Fork failed */
if(p == 0) { /* child */
close(pipe_stdin[1]);
dup2(pipe_stdin[0], 0);
close(pipe_stdout[0]);
dup2(pipe_stdout[1], 1);
execl("/bin/sh", "sh", "-c", cmdline, 0);
perror("execl"); exit(99);
}
childinfo->child_pid = p;
childinfo->to_child = pipe_stdin[1];
childinfo->from_child = pipe_stdout[0];
return 0;
}

#define TESTING
#ifdef TESTING
int main(void) {
char buf[1000];
struct popen2 kid;
popen2("tr a-z A-Z", &kid);
write(kid.to_child, "testing\n", 8);
close(kid.to_child);
memset(buf, 0, 1000);
read(kid.from_child, buf, 1000);
printf("kill(%d, 0) -> %d\n", kid.child_pid, kill(kid.child_pid, 0));
printf("from child: %s", buf);
printf("waitpid() -> %d\n", waitpid(kid.child_pid, NULL, 0));
printf("kill(%d, 0) -> %d\n", kid.child_pid, kill(kid.child_pid, 0));
return 0;
}
#endif

关于c++ - 我们有类似 C 或 C++ 中的 perl 的 IPC::Open3 的东西吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48316811/

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