My problem is in line read(pipe1[0], path1, pathLength1);
where for some reason variable path1
has contains additional characters. For example I enter path "./test.txt"
which contains 10 characters, then send it trough pipe, and this read()
line of code sets path1
variable to "./test.txt"
and then plus some 4 random characters (14 characters total). Can you tell me what am I doing wrong?
I found work around by adding terminate character manually, but I still don't know what's the problem.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <sys/wait.h>
int main(){
int pipe1[2], pid;
if(pipe(pipe1) < 0)
{
printf("Greska prilikom kreiranja datavoda!\n");
// exit(-1);
}
// Parent process
if(pid = fork() != 0){
char path[100], key[100];
printf("Unesite putanju do fajla koji treba otvoriti \n");
scanf("%s", path);
printf("Unesite kljucnu rec koju treba traziti u fajlu\n");
scanf("%s", key);
printf("Putanja koju ste uneli je: %s, a kljucna rec: %s\n", path, key);
close(pipe1[0]);
int pathLength = strlen(path);
int keyLength = strlen(key);
write(pipe1[1], &pathLength, sizeof(pathLength));
write(pipe1[1], &keyLength, sizeof(keyLength));
write(pipe1[1], path, pathLength);
write(pipe1[1], key, keyLength);
wait(NULL);
close(pipe1[1]);
}
// Child Process
else
{
char path1[100], key1[100];
int pathLength1, keyLength1;
close(pipe1[1]);
read(pipe1[0], &pathLength1, sizeof (pathLength1));
read(pipe1[0], &keyLength1, sizeof (keyLength1));
read(pipe1[0], path1, pathLength1);
read(pipe1[0], key1, keyLength1);
// For some reason strlen(path1) is 14 ?
path1[pathLength1] = '\0';
key1[keyLength1] = '\0';
printf("Proces dete primio put: %s i kljucnu rec: %s\n", path1, key1);
FILE *f;
f = fopen(path1, "r");
if(f == NULL){
printf("Greska prilikom otvaranja fajla!");
}
int i=0;
while(!feof(f)){
i++;
char tmp[500];
fgets(tmp, sizeof(tmp), f);
if(strstr(tmp, key1) != NULL)
printf("Kljucna rec se nalazi u liniji: %d\n", i);
}
fclose(f);
close(pipe1[0]);
}
return 0;
}