c - Using dup,pipe,fifo to communicate with the child process -


i trying sample program read data beginning of file 2 processes using fork().

when fork() called, kernel creates child process, , child process inherits properties of parent process. open files , file descriptors. aim read file beginning both child , parent. tried create separate descriptors using dup2(), not working.

my second question is there way make child process continue processing task after completing initial task. (signal has send parent ask task? , parent communicating 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 understand

(1) loreb mention in comments, dup2 duplicates file descriptor. wit man (2) dup2:

after successful return 1 of these system calls, old , new file descriptors may used interchangeably. refer same open file description (see open(2)) , share file offset , file status flags; example, if file offset modified using lseek(2) on 1 of descriptors, offset changed other.

so got off bad assumption. close , open file second time in child.

(2) dup2 signature int dup2(int oldfd, int newfd). doing dup2(fd1, fd) fd descriptor want duplicate have parms reversed.

(3) local variables not initialized so

int fd1,fd2; 

have random values. when dup2(fd1, fd) trying use whatever random value in fd1 if (normally) greater 1023 going cause call fail ebadf.

(4) wait() takes parameter should @ least wait(null).

(5) always check return values on system calls. dups, reads, etc., failing.

i recommend getting work , submitting second question separate post.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -