I'm trying to gain a better understanding of fork()
and concurrency in c
programming. I'm a novice, and I'm having trouble understanding the logic. I tried to make a simple producer-consumer program using fork()
. basically, a producer()
function should take a character from stdin
, and write it to a file. At the same time, a second process runs the consumer
code, which is supposed to read the last character in the file and echo it to the screen. The producer()
and consumer()
functions are working fine by themselves, i.e. they are doing what each are supposed to do, but the problem is in the concurrency. Here is my code:
#include<stdio.h>
#include <stdlib.h>
#include <unistd.h>
FILE* fp;
//char c;
void producer(){
char c=' ';
while(c!='x'){
puts("enter a char");
c = getchar();
while((fp = fopen("shared.txt", "at"))==NULL); //while the file is in use by another program
fputc(c,fp);
if(c!='\n')puts("file written to successfully");
fclose(fp);
}
return;
}
char readChar(){
char c;
while((fp = fopen("shared.txt", "rt"))==NULL);
fseek(fp, -1, SEEK_END);
c = fgetc(fp);
fclose(fp);
return c;
}
void consumer(){
char c;
do{
c = readChar();
printf("This is the latest character supplied: %c\n", c);
}while(c!='x');
}
int main(){
int pid = fork(); //now we fork processes
if(pid ==0 ){
producer(); //the child process should run and create some text in the file
}else{
wait(); consumer();
}
}
I tried to add wait statements after the calls to producer()
and consumer()
in their respective branches, but basically no matter what, the program fails to do what I want . if in main ()
I have
int main(){
int pid = fork(); //now we fork processes
if(pid ==0 ){
producer(); //the child process should run and create some text in the file
}else{
consumer();
}
}
I get stuck in an infinite loop. Adding wait();
after the function call in one or both branches doesn't help, because the infinite loop occurs before control passes to either wait()
.
If I try this:
int main(){
int pid = fork(); //now we fork processes
if(pid ==0 ){
producer(); //the child process should run and create some text in the file
}else{
wait(); consumer();
}
}
I can enter text from the stdin
until I enter 'x'
, but then as expected the consumer reads only the last character written to the file.
Is there a way to get this to work with wait statements?