题
我正在编写一个小程序,这是应该做的。
在主要过程中,我必须创建一个新的过程,并且应该执行另一个程序,该程序仅执行printf(“ text”)。我想在Stdout上重定向管道写入端,主过程应从其管道上读取并在Stdout上打印。我编写了代码,但是当父进程试图从管道中读取时,我一次又一次会得到一个细分错误。
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
void write_to(FILE *f){
char buf[50];
fprintf(f,"KOMA");
}
int main(){
int cpPipe[2];
int child1_fd;
int child2_fd;
if(pipe(cpPipe) == -1){
fprintf(stderr,"ERROR PIPE creation");
exit(1);
}else{printf("pipe couldn't be created\n");}
child1_fd = fork();
if(child1_fd < 0){
fprintf(stderr, " CHILD creation error");
exit(1);
}
if(child1_fd == 0){
printf("*CHILD*\n");
char program[] = "./Damn";
int dupK;
printf("stdout %d \n", STDOUT_FILENO);
printf("stdin %d \n", STDIN_FILENO);
printf("pipe1 %d \n", cpPipe[1]);
printf("pipe0 %d \n", cpPipe[0]);
// closing pipe write
close(cpPipe[0]);
close(1);
dup(cpPipe[1]);
printf("and");
close(cpPipe[1]);
exit(0);
}else{
printf("*Parent*\n");
char *p;
char *buf;
FILE *pipe_read;
close(cpPipe[1]);
pipe_read = fdopen(cpPipe[0],"r");
while((buf = fgets(p,30,pipe_read)) != NULL){
printf("buf %s \n", buf);
}
wait();
printf("Child is done\n");
fclose(pipe_read);
exit(0);
}
}
重定向到它时,我必须关闭管道写的结尾吗?
解决方案
嗯,...您的细分错误的原因在这里:
buf = fgets(p,30,pipe_read);
P是实质上无处不在的指针。它的内容是执行时堆栈中的任何内容,您永远不会初始化它。您需要它指向您可以使用的大量内存!分配返回 malloc()
致电或声明为 char p[LEN]
.
编辑:您还将重新打开已经打开的文件描述符。检查文档 fgets
和 pipe
, ,我认为您对它们的工作方式感到困惑。
也就是说,您功能的流程有点令人困惑。尝试澄清它!请记住,代码旨在表达意图,功能思想。尝试使用铅笔和纸来组织您的程序,然后将其写入实际代码:)。
干杯!
其他提示
重定向到它时,我必须关闭管道写的结尾吗?
通常,是的,因为虽然管道的写入末端有一个过程,但读取管道的过程将不会获得EOF,并且会悬挂。当然,关闭您不会使用的文件描述符也是一个整理。
您的代码还表示在成功路径中“无法创建管道”。
不隶属于 StackOverflow