Tuesday, 10 September 2013

Passing a structure through a FIFO

Passing a structure through a FIFO

I have written a simple code where one process is passing a structure to
another process, the parent process is writing the data, but child process
is not able to access it. I have used fork() system call to create two
processes. But i have problem here the parent process i called twice and
child process is also called twice when i run the program. Can any one let
me know what mistake i am doing.
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <errno.h>
#include <sys/errno.h>
#include <fcntl.h>
#include <string.h>
#define MAX_LINE_LEN 100
#define FIFO_NAME "my_fifo"
typedef struct student_info {
char *name;
int age;
char *sex;
}student;
int w_byte_parent = 0, r_byte_parent = 0;
int w_byte_child = 0, r_byte_child = 0;
void do_child() {
int fifo;
char buffer[MAX_LINE_LEN];
int i = 0;
student child;
printf("Child opening FIFO \n");
if( (fifo = open(FIFO_NAME, O_RDWR)) < 0 ) {
perror("open in child failed");
exit(EXIT_FAILURE);
}
printf("Child reading from FIFO \n");
r_byte_child = read(fifo, child, sizeof(student));
if(r_byte_child < 0)
printf("Read failed by child process\n");
printf("%d Bytes read by child process\n", r_byte_child);
}
int main(int argc, char **argv) {
int fifo;
char buffer[MAX_LINE_LEN];
int ch = 0, i = 0;
/*
** Create a FIFO
*/
/* Parent creating FIFO */
if( (mkfifo(FIFO_NAME, 0666)) < 0) {
if( errno != EEXIST ) {
perror( "mkfifo" );
exit( EXIT_FAILURE );
}
}
/*
** Create other process
*/
switch(fork()) {
case -1:
perror("fork()");
exit(EXIT_FAILURE);
case 0: /* Child Process */
do_child();
break;
default:/* Parent Process */
break;
}
/* Pass a structure to FIFO */
student *info;
info = (student *)malloc( sizeof (student)) ;
info->name = (char *)calloc(sizeof(char), 10);
strcpy(info->name, "jack");
info->age = 27;
info->sex = (char *)calloc(sizeof(char), 10);
strcpy(info->sex , "Male");
/* Parent Opening FIFO */
printf("parent opening FIFO \n");
if( (fifo = open(FIFO_NAME, O_RDWR)) < 0 ) {
perror("open in parent failed");
exit(EXIT_FAILURE);
}
/*
** Write some thing into FIFO so child can read it
*/
printf("parent writing to FIFO \n");
w_byte_parent = write( fifo, info, sizeof(struct student_info));
if(w_byte_parent < 0)
printf("Nothing was written to FIFO by parent\n");
printf("Wrote %d bytes to FIFO\n",w_byte_parent);
}

No comments:

Post a Comment