The Open Source Swiss Army Knife

/code/c/unix_c/fork/
/code/c/unix_c/fork/ + sub-categories
http://www.sirfsup.com/
web directory content
    
      

Not logged in
Chat Register Login
return to:  http:/www.sirfsup.com      /code   /c   /unix_c   /fork 
Permalink: fork.c
Title: pipe to do IPC after fork example
article options : please login   |  raw source view  

/****************************************************************
 *
 * Purpose: Basic example of pipe. 
 *          Read and write fixed length records across a pipe.
 *          This is about a simple as they come...
 *
 * Author:  M J Leslie
 *
 * Date:    17 Apr 96
 *
 ****************************************************************/

#include <sys/types.h>
#include <unistd.h>			/* pipe.		*/
#include <signal.h>
#include <string.h>  // strlen
#include <stdio.h>   // printf
void Child  (pid_t Handle);
void Parent (pid_t Handle);

int main(void)
{

  pid_t		Pid;
  int 		fd[2];

  pipe(fd);				/* Create two file descriptors 	*/

  if ( (Pid = fork()) < 0)  {
	printf("error with fork return < 0\n");
	return -1;
  }
  printf("pid of forked process = %d\n", (int)Pid);   // prints 12839 then prints 0
  if ( Pid == 0)			/* Child			*/
  {
    close(fd[0]);
    Child(fd[1]);
    puts("Child end");
  }
  else					/* Parent.			*/
  {
    close(fd[1]);
    Parent(fd[0]);
    puts("Parent end");
    sleep(10);  // see the zombie in the ps!!
  }
  return 0;  // after exit zombie is cleaned up default-wise
}

/****************************************************************
 *
 *      The Child sends data to the parent.
 *
 ****************************************************************/

void Child(pid_t Handle)
{
  char Buff[]="Martin 1 abcdefghijklmnop ";

  write(Handle, Buff, strlen(Buff)+1);

  Buff[7] = '2';
  write(Handle, Buff, strlen(Buff)+1);

  Buff[7] = '3';
  write(Handle, Buff, strlen(Buff)+1);

  Buff[7] = '4';
  write(Handle, Buff, strlen(Buff)+1);  
  
  close(Handle);
}

/****************************************************************
 *
 *      Read the data sent by the child.
 *
 ****************************************************************/


void Parent(pid_t Handle)
{

  char Buff[50];

  /* ...	Read EXACTLY the number of bytes sent. 
     ...	0 is returned when the pipe is closed by the child. */

  while (read(Handle,Buff, 27) > 0)
  {
    printf("%s\n", Buff);
  }
      
}






Leave a Reply
Your Name:     anonymous
Your Email:
Website:  
Comments:

The author will be notified of your reply.
return to top