[英]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.