[英]Simple multiple child exec'd fork segfaulting when trying to read from stdout of child
我建立了一个简单的fork示例,以fork和exec 2个孩子为例,然后通过管道读取它们的输出,但是我遇到了段错误(发生在close(piping [i] [1]);),并且找不到原因。 请参见下面的代码:
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int reader(int *piping[]) {
char readstring[50];
char readstring2[50];
FILE *outPut;
FILE *outPut2;
outPut = fdopen(piping[0][0], "r");
outPut2 = fdopen(piping[1][0], "r");
fgets(readstring, sizeof(readstring), outPut);
fgets(readstring2, sizeof(readstring2), outPut2);
printf("%s\n", readstring);
printf("%s\n", readstring2);
return 0;
}
int main(void) {
int i;
int j;
int pid;
int **piping = malloc(sizeof(int*) *2);
for(i = 0; i < 2; ++i) {
piping[i] = malloc(sizeof(int) *2);
}
for(j = 0; j < 2; ++j) {
pipe(piping[j]);
if((pid = fork()) == -1)
fprintf(stderr, "error reading pipe\n");
exit(1);
} else if(pid == 0) {
//child
//close read pipes dup2 write pipes to stdout
//then close old write pipes
close(piping[j][0]);
if(dup2(piping[j][1], 1) == -1) {
fprintf(stderr, "error dup2");
exit(2);
}
close(piping[j][0]);
close(1);
if(execlp("./playex", "playex", NULL)) {
fprintf(stderr, "exec error\n");
}
} else {
//parent
close(piping[j][1]);
}
}
reader(piping);
}
上面是管道和执行程序应读取的主要功能,下面是运行的基本程序。
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
fprintf(stdout, "go\n");
}
我尝试过运气好的方式来修复段错误,请帮助查找和解决问题。
您的主要问题是(在编辑问题以隐藏其最初显示的内容之前)您正在书写的管道数组范围之外:
for(i = 0; i < 2; ++i) {
piping[i] = malloc(sizeof(int) *2);
}
for(j = 0; j < 2; ++j) {
pipe(piping[i]);
您正在索引j
而不是i
的第二个循环,因此您使用的是未分配的piping[2]
。 冲洗并重复。
您可以通过删除i
和j
的当前定义并使用以下方法来避免该错误:
for (int i = 0; i < 2; ++i) {
piping[i] = malloc(sizeof(int) *2);
}
for (int j = 0; j < 2; ++j) {
pipe(piping[i]);
现在, i
将在第二个循环中未定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.