How to make three processes work in C/C++ -
i have make 3 processes a, b , c use shared memory. , b write 100 integers in shared memory, , c reads them , writes them binary file. made, doesn't work properly. include <stdio.h>
, <math.h>
, <fcntl.h>
, <time.h>
. how make work?
struct sync { int n; int lock; int generated; char process; } *b; int testandset(int* lockptr) { int oldvalue = *lockptr; return 0 != oldvalue; } int main() { struct sync buff; int pid, ppid, fp, i; srand(time(null)); b = (struct sync*)malloc(666); b->n = 0; b->lock = 0; b->generated = 0; = 0; printf("generating numbers\n"); pid = fork(); if (0 == pid) { while (100 >= b->generated) { while (testandset(&(b->lock))) { } buff.n = rand() % 1001; buff.process = 'a'; fp = open("db", o_rdwr | o_append); if (-1 == fp) fp = open("db", o_creat); write(fp, &buff, sizeof(struct sync)); close(fp); b->generated++; b->lock = 0; } } if (0 < pid) { ppid = fork(); if (0 == ppid) { while (100 >= b->generated) { while (testandset(&(b->lock))) { } buff.n = rand() % 1001; buff.process = 'b'; printf("no: %d %d \n", ++i, buff.n); fp = open( "db", o_rdwr | o_append ); if (-1 == fp) fp = open("db", o_creat); write(fp, &buff, sizeof(struct sync)); close(fp); b->generated++; b->lock = 0; } } if (0 < ppid) { wait(); = 0; fp = open("db", o_rdonly, 0755); printf("reading file\n"); while (read(fp, &buff, sizeof(struct sync))) { if ('a' == buff.process) i++; } close(fp); int vals[i]; = 0; fp = open("db", o_rdonly, 0666); while (read(fp, &buff, sizeof(struct sync))) { if ('a' == buff.process) vals[i++] = buff.n; } close(fp); fp = open("db", o_rdonly, 0455); int i; for(i = 0; < i; i++) write((const void*) &vals[i],sizeof(int),1,fp); } wait(); } return 0; }
files not reliable mutliprocess sharing information (and editing @ same time), you'd rather use real database in transaction mode or use ipc http://www.cs.cf.ac.uk/dave/c/node27.html. or maybe re-design , use threads , mutex.
Comments
Post a Comment