I am writing a program that reads integers from a file and puts them into shared memory. The purpose of the program is to add the integers up using two different divide and conquer techniques using forked processes and shared memory. I can't seem to get the integers to read into a variable, let alone shared memory. The file if integers is formatted such that there is one integer per line. The function I use to count the number of integers in a file simply counts the number of lines in said file. Here's the code:
project1.h
Code:
#ifndef PROJECT1_H
#define PROJECT1_H
#include <stdio.h>
int count( FILE *fp );
#endif
project1.c
Code:
#include "project1.h"
int count( FILE *fp )
{
char buff[8];
int i;
rewind( fp );
while( fgets( buff, sizeof( buff ), fp ) != NULL )
i++;
return( i );
}
master.c
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "project1.c"
#define KEY 45386
#define BUFF_SZ sizeof( int )
int main()
{
int i;
int shmid;
char j;
FILE *fp;
// Test to see if the program opened numbers.dat successfully.
fp = fopen( "numbers.dat", "r" );
if( fp == NULL )
{
perror( "master: Error: fopen: Can't open numbers.dat to read.\n");
return( 1 );
}
// Test to see if shmget was successful.
shmid = shmget( KEY, BUFF_SZ * count( fp ), 0777 | IPC_CREAT );
if( shmid == -1 )
{
perror( "master: Error: shmget: Cannot allocate shared memory" );
return( 1 );
}
// This initializes the pointers the program will use to
// access shared memory.
char * paddr = ( char * )( shmat ( shmid, 0, 0 ) );
int * pint = ( int * )( paddr );
// This reads the contents of the file "numbers.dat" into the array
// of integers I allocated earlier in the program.
for( i = 0; i < count( fp ) * 2; i++)
if( (j = getc( fp ) ) != '\n' )
paddr[i] = j;
// This executes bin_adder to add the numbers in shared memory.
execl( "./bin_adder", 0 );
// These two commands clean up the mess I have made. They close the opened
// file and unallocates the shared memory that was allocated earlier.
shmctl( shmid, IPC_RMID, 0 );
fclose( fp );
return( 0 );
}
bin_adder.c
Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "project1.c"
#define KEY 45386
#define BUFF_SZ sizeof( int )
int main()
{
int shmid;
FILE *fp;
// Test to see if the program opened numbers.dat successfully.
fp = fopen( "numbers.dat", "r" );
if( fp == NULL )
{
perror( "master: Error: Can't open numbers.dat to read.\n");
return( 1 );
}
shmid = shmget( KEY, BUFF_SZ * count( fp ), 0777 );
int * cint = ( int * )( shmat ( shmid, 0, 0 ) );
printf( "bin_adder: %d is stored in shared memory.\n", *cint );
fclose( fp );
return( 0 );
}
I feel really stupid, but I am just not comfortable with working with files yet. Could someone point me in the right direction? Thanks.