I am trying a sample program to read the data from the beginning of the file by two processes using the fork().
When fork() is called, kernel creates a child process, and this child process inherits the properties of the parent process. All the open files and the file descriptors. My aim is to read the file from the beginning by both the child and the parent. I tried to create separate descriptors using dup2(), but its not working.
My second question is that is there any way to make the child process to continue processing another task after completing the initial task. (signal has to be send to the parent to ask for another task? and parent will be communicating with the child through pipe or fifo)
int main(int argc, char* argv[]){
int fd1,fd2;
int fd;
int read_bytes;
pid_t pid;
char* buff;
buff = malloc(sizeof(buff)*5);
if(argc < 2){
perror("\nargc: Forgot ip file");
return 1;
}
fd = open(argv[1],O_RDONLY);
if(-1 == fd){
perror("\nfd: ");
return 2;
}
pid = fork();
if(pid == -1){
perror("\n pid");
return 1;
}
else if(pid == 0){ // CHILD
dup2(fd1,fd);
read_bytes = read(fd1,buff,5);
printf("\n %s \n",buff);
}
else{ //PARENT
wait();
printf("\n Parent \n");
dup2(fd2,fd);
//close(fd);
read_bytes = read(fd2,buff,5);
printf("\n %s \n",buff);
}
return 0;
}
Please help to understand