I'm having trouble with a forking program.
One process writes to a file, the other waits for the file to be written, prints something out, then deletes it. They essentially process in order based on whether the file is there or not.
The processes should be outputting more useful information than this. As it is, this is the output:
Waiting for data.txt to appear...
Found it! Splitting now.
Producer initialized!
Waiting for values.txt to disappear...
Consumer initialized!
Waiting for values.txt to appear...
Values.txt found! Processing...
Values.txt is gone: processing...
Then both seem to terminate, but I can't tell because they don't finish.
I just need a little push and I should be able to figure the rest out myself.
//includes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
int main (int argc, char *argv[]) {
int prodpid;
int conspid;
FILE *fin;
printf("Waiting for data.txt to appear...\n");
do {
fin=fopen("data.txt", "rt");
}while(fin==NULL);
printf("Found it! Splitting now.\n");
prodpid=fork();
if(prodpid==0){
char *c=(char*)malloc(4);
FILE *fval;
printf("Producer initialized!\n");
while(fgets(c, 4, fin)!=NULL){
printf("Waiting for values.txt to disappear...\n");
do {
fval=fopen("values.txt", "rt");
}while(fval!=NULL);
printf("Values.txt is gone: processing...\n");
int i;
char line[2*i+2];
char buffer[100];
for(i=atoi(c); i>=0; i--){
sprintf(buffer, "%i", i);
strcat(line, buffer);
strcat(line, " ");
}
fwrite(line, 1, sizeof(line), fopen("values.txt", "w"));
printf("Done writing %s.\n", line);
fclose(fval);
}//done with all of the numbers in data.txt
fclose(fin);
}else{
conspid=fork();
if(conspid==0){
int cnt=0;
char *c=(char*)malloc(1024);
FILE *fval;
printf("Consumer initialized!\n");
while(1){
printf("Waiting for values.txt to appear...\n");
do {
fval=fopen("values.txt", "rt");
}while(fval==NULL);
printf("Values.txt found! Processing...\n");
cnt++;
fgets(c, 1024, fval);
int num=atoi(strtok(c," "));
printf("Processing VALUES.TXT file number %i with values %s\nIt has %i odd numbers\n", cnt, c, num/2+1);
fclose(fval);
system("rm values.txt");
}
}else{wait(conspid);}
}
wait(prodpid);
return 0;
}