The site is loading…

https://docs.google.com/document/d/1SivPVqXB9kCiKycBCkvScJMFX84xeHjVY0WMqkMNjxs/edit

  1. /****************************************************************
  2.  *
  3.  * Purpose: Basic example of pipe. 
  4.  *          Read and write fixed length records across a pipe.
  5.  *          This is about a simple as they come...
  6.  *
  7.  ******************************************************************/
  8.  
  9. #include <sys/types.h>
  10. #include <unistd.h>			/* pipe.		*/
  11. #include <signal.h>
  12.  
  13. void Child  (int Handle);
  14. void Parent (int Handle);
  15.  
  16. void main()
  17. {
  18.  
  19.   pid_t		Pid;
  20.   int 		fd[2];
  21.  
  22.   pipe(fd);				/* Create two file descriptors 	*/
  23.  
  24.   Pid = fork();
  25.  
  26.   if ( Pid == 0)			/* Child			*/
  27.   {
  28.     close(fd[0]);
  29.     Child(fd[1]);
  30.     puts("Child end");
  31.   }
  32.   else					/* Parent.			*/
  33.   {
  34.     close(fd[1]);
  35.     Parent(fd[0]);
  36.     puts("Parent end");
  37.   }
  38. }
  39.  
  40. /****************************************************************
  41.  *
  42.  *      The Child sends data to the parent.
  43.  *
  44.  ****************************************************************/
  45.  
  46. void Child(int Handle)
  47. {
  48.   char Buff[]="Martin 1 abcdefghijklmnop ";
  49.  
  50.   write(Handle, Buff, strlen(Buff)+1);
  51.  
  52.   Buff[7] = '2';
  53.   write(Handle, Buff, strlen(Buff)+1);
  54.  
  55.   Buff[7] = '3';
  56.   write(Handle, Buff, strlen(Buff)+1);
  57.  
  58.   Buff[7] = '4';
  59.   write(Handle, Buff, strlen(Buff)+1);  
  60.  
  61.   close(Handle);
  62. }
  63.  
  64. /****************************************************************
  65.  *
  66.  *      Read the data sent by the child.
  67.  *
  68.  ****************************************************************/
  69.  
  70.  
  71. void Parent(int Handle)
  72. {
  73.  
  74.   char Buff[50];
  75.   /* ...	Read EXACTLY the number of bytes sent. 
  76.      ...	0 is returned when the pipe is closed by the child. */
  77.  
  78.   while (read(Handle,Buff, 27) > 0)
  79.   {
  80.     printf("%sn", Buff);
  81.   }
  82.  
  83. }

Leave a Reply