问题描述
如问题所示。我可以连接 2 个进程(父进程和子进程)通过 pipe() 发送信息但不使用 stdout、stdin 或 stderr 吗?我可以创建一个新的流或缓冲区来使用吗?
编辑:
我的子进程通过 execl() 启动一个新程序,该程序需要通过管道与第一个程序通信,而不使用 stdin 和 stdout。
我目前用于通过这些流进行通信的代码如下:
#define READ 0
#define WRITE 1
pid_t
popen2(const char *command,int *infp,int *outfp)
{
int p_stdin[2],p_stdout[2];
pid_t pid;
if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0)
return -1;
pid = fork();
if (pid < 0)
return pid;
else if (pid == 0)
{
close(p_stdin[WRITE]);
dup2(p_stdin[READ],READ);
close(p_stdout[READ]);
dup2(p_stdout[WRITE],2);
execl("/bin/bash","bash","-c",command,NULL);
perror("execl");
exit(1);
}
if (infp == NULL)
close(p_stdin[WRITE]);
else
{
*infp = p_stdin[WRITE];
}
if (outfp == NULL)
close(p_stdout[READ]);
else
{
*outfp = p_stdout[READ];
}
return pid;
}
我目前正在与我的子进程中的 stdin 读取和写入 stdout 进行通信。如果我想从我创建的不同缓冲区读取和写入以防止由于打印和错误可能导致的数据损坏怎么办?可能吗?
解决方法
井管用于您提到的确切目的。
这是 Beej 指南中的一个示例。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
int pfds[2];
char buf[30];
pipe(pfds);
if (!fork()) {
printf(" CHILD: writing to the pipe\n");
write(pfds[1],"test",5);
printf(" CHILD: exiting\n");
exit(0);
} else {
printf("PARENT: reading from pipe\n");
read(pfds[0],buf,5);
printf("PARENT: read \"%s\"\n",buf);
wait(NULL);
}
return 0;
}
更多信息:https://beej.us/guide/bgipc/html/multi/pipes.html#pipesclean