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.

#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");
	printf("Found it! Splitting now.\n");
		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");

			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);
		}//done with all of the numbers in data.txt
			int cnt=0;
			char *c=(char*)malloc(1024);
			FILE *fval;
			printf("Consumer initialized!\n");
				printf("Waiting for values.txt to appear...\n");
				do {
					fval=fopen("values.txt", "rt");
				printf("Values.txt found! Processing...\n");
				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);
				system("rm values.txt");
return 0;

Sorry, this was a careless error that took me too long to find. Please delete this thread (or show me how).

This article has been dead for over six months. Start a new discussion instead.