Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

c - Interpretation of pipes

I have two codes related on pipes and I′d like to share what I understand the code would do. I am starting with this pipe thing, so I want to get it well. The first code is:

main (){  
  int fd[2];  
  char c;  
  fork();  
  pipe(fd);  
  read(fd[0], &c, 1);  
  wait(NULL);
}

I think in this what′s happening is the main process creates a child process and then a pipe. The parent awaits the death of his child. The child tries to read a character from the pipe, but because the pipe is empty, the child gets stuck. Therefore, both processes are blocked. Is this right?

The second code is:

main (){  
  int n = getpid() ;  
  char s[80] ;  
  fork() ; /? 1 ?/  
  if (getpid() == n) fork() ; /? 2 ?/  
  fork(); /* 3 */  
  if (getppid() != n) fork() ; /? 4 ?/  
  if (getppid() == n) {    
      sprintf( s , "%d
" , getpid() ) ;    
      write( 1 , s , strlen(s) ) ;   
  }
}

In this second, I think the main process creates two child processes and two other possible child processes. First a child is created and then see if the process identification number corresponds to n, in which case another child is created. Another new child is then created and finally checked to see if the parent process ID number matches the process ID number. If it is false, the last child is created, but if it is true, the process identifier number is printed on the screen and finally the parent writes in the s parameter.

Are my interpretations good?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...