问题描述
我正在生成一个带有stdin和stdout的子进程,并将其设置为父子进程之间的管道。我想通过管道将管道插入孩子,并且-现在-将它们回显。使用标准cat
可以正常工作,但是使用我自己基于getline()
的cat-clone则不能。我看不出是什么问题。
这些实际上是另一个问题的MCVE,但现在我无法使它们正常工作。
基于https://jineshkj.wordpress.com/2006/12/22/how-to-capture-stdin-stdout-and-stderr-of-child-program/的分叉程序
#include <unistd.h>
#include <stdio.h>
/* since pipes are unidirectional,we need two pipes.
one for data to flow from parent's stdout to child's
stdin and the other for child's stdout to flow to
parent's stdin */
#define NUM_PIPES 2
#define PARENT_WRITE_PIPE 0
#define PARENT_READ_PIPE 1
int pipes[NUM_PIPES][2];
/* always in a pipe[],pipe[0] is for read and
pipe[1] is for write */
#define READ_FD 0
#define WRITE_FD 1
#define PARENT_READ_FD ( pipes[PARENT_READ_PIPE][READ_FD] )
#define PARENT_WRITE_FD ( pipes[PARENT_WRITE_PIPE][WRITE_FD] )
#define CHILD_READ_FD ( pipes[PARENT_WRITE_PIPE][READ_FD] )
#define CHILD_WRITE_FD ( pipes[PARENT_READ_PIPE][WRITE_FD] )
void
main()
{
int stdout_copy = dup(STDOUT_FILENO);
int stdin_copy = dup(STDERR_FILENO);
printf("Starting\n");
int outfd[2];
int infd[2];
// pipes for parent to write and read
pipe(pipes[PARENT_READ_PIPE]);
pipe(pipes[PARENT_WRITE_PIPE]);
if(!fork()) {
// char *argv[]={ "/usr/bin/cat",0};
char *argv[]={ "./getline",0};
printf("Child\n");
dup2(CHILD_READ_FD,STDIN_FILENO);
dup2(CHILD_WRITE_FD,STDOUT_FILENO);
/* Close fds not required by child. Also,we don't
want the exec'ed program to kNow these existed */
close(CHILD_READ_FD);
close(CHILD_WRITE_FD);
close(PARENT_READ_FD);
close(PARENT_WRITE_FD);
execv(argv[0],argv);
} else {
printf("Parent\n");
char buffer[100];
int count;
/* close fds not required by parent */
close(CHILD_READ_FD);
close(CHILD_WRITE_FD);
// Write to child’s stdin
write(PARENT_WRITE_FD,"2^32\n",5);
write(PARENT_WRITE_FD,"\n\4",2);
// Read from child’s stdout
sleep(1);
count = read(PARENT_READ_FD,buffer,sizeof(buffer)-1);
dup2(stdout_copy,STDOUT_FILENO);
dup2(stdin_copy,STDIN_FILENO);
fprintf(stderr,"E:Read %i\n",count);
printf("Read %i\n",count);
if (count >= 0) {
buffer[count] = 0;
printf("%s",buffer);
} else {
printf("IO Error\n");
}
}
}
我的猫克隆:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc,char** argv) {
char* buffer = malloc(1024);
size_t n=0;
int r=0;
FILE* f = stdin;
while( r>=0 ) {
r=getline(&buffer,&n,f);
printf("%i/%i: %s\n",r,n,buffer);
buffer[0]=0;
}
return 0;
}
输出为cat
:
Starting
Parent
Child
E:Read 7
Read 7
2^32
使用cat
-克隆“ getline”的输出:
Starting
Parent
Child
我在Windows 10上的MinGW中。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)