I am studying low level I/O in C and multiprocess programming with fork().
In this example the parent process exchanges information about input files with the child processes. However, reading the second input file generates the Bad address error, why?
#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;
}
inputF1 content: abcdefghi
inputF2 content: abcd
All files are in the same directory
I run the program like this:
./pipe inputF1 inputF2 outputF
Error:
errore lettura inputF2: Bad address
Segmentation fault (core dumped)
EDIT
The problem was uninitialized char * char_input, thanks Mickael B. Anyway the program now freezes and waits for something. Is there any problem with pipes?
You have
char *char_input;
// ...
read(inputF2, char_input, 1)
But char_input
is uninitialised
So you can do this
char char_input[2];