gpt4 book ai didi

C 低级 I/O : Bad address when reading a file

转载 作者:行者123 更新时间:2023-11-30 14:32:51 25 4
gpt4 key购买 nike

我正在研究 C 语言中的低级 I/O 以及使用 fork() 的多进程编程。

在此示例中,父进程与子进程交换有关输入文件的信息。但是,读取第二个输入文件会生成错误地址错误,为什么?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char* argv[]){

if(argc != 4){
printf("Numero di parametri non valido");
exit(1);
}

int pipe1[2], pipe2[2];

if(pipe(pipe1) < 0){
perror("errore pipe");
exit(-1);
}
if(pipe(pipe2) < 0){
perror("errore pipe");
exit(-1);
}



int pid;
int pid2;

if((pid = fork()) < 0){
perror("errore fork");
exit(-1);
}






if(pid == 0){ //first child
char buff[2];

close(pipe1[0]);

int inputF1;
if((inputF1 = open(argv[1], O_RDONLY)) < 0)
perror("errore open inputF1");

int n;

while((n = read(inputF1, buff, 2)) > 0){
write(pipe1[1], buff, 2);
}

close(pipe1[1]);
close(inputF1);
}

else{

if((pid2 = fork()) < 0){
perror("errore fork");
exit(-1);
}

if(pid2 == 0){ //second child
char buff2[2];

close(pipe2[1]);

int outputF;
if((outputF = open(argv[3], O_RDWR | O_APPEND)) < 0)
perror("errore open outputF");

int n2;

while((n2 = read(pipe2[0], buff2, 2)) > 0){
if((write(outputF, buff2, 2)) != 2)
perror("errore scrittura outputF");
}

close(pipe2[0]);
close(outputF);
}

else{ //parent process
char buff0[2];
char *char_input;

close(pipe1[1]);
close(pipe2[0]);


int n_padre;
int n_input;

int inputF2;
if((inputF2 = open(argv[2], O_RDONLY)) < 0)
perror("errore open inputF2");

while((n_padre = read(pipe1[0], buff0, 2)) > 0){
if((n_input = read(inputF2, char_input, 1)) != 1)
perror("errore lettura inputF2");

if(char_input[0] != buff0[0] && char_input[0] != buff0[1])
write(pipe2[1], buff0, 2);
}

close(pipe1[0]);
close(pipe2[1]);
close(inputF2);
}
}

return 0;

}

输入F1内容:abcdefghi

输入F2内容:abcd

所有文件都在同一目录中

我这样运行程序:

./pipe inputF1 inputF2 outputF

错误:

错误lettura inputF2:地址错误

段错误(核心转储)

编辑

问题是未初始化的 char * char_input,谢谢 Mickael B.不管怎样,程序现在卡住并等待一些东西。管道有问题吗?

最佳答案

你有

char *char_input;
// ...
read(inputF2, char_input, 1)

但是char_input未初始化

所以你可以这样做

char char_input[2];

关于C 低级 I/O : Bad address when reading a file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59651895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com