for an exercise in a UNIX OS class I am supposed to develop a program with two sibling processes communicating through a pipe. One process (producer) is supposed to read strings from stdout and send them to the other process (consumer) which then has to convert the string to uppercase and print it again to stdout. The string "end" terminates both siblings and the parent process.
The program works fine however it breaks down when trying to read whole phrases from the user instead of single strings.
Here is a part of my main:
int main(void) {
int child_status, fd[2];
if (pipe(fd)) {
fprintf(stderr, "Error: Could not create pipe.\n");
return EXIT_FAILURE;
}
if (!fork()) {
// child1
producer(fd);
exit(0);
} else if (!fork()) {
// child2
consumer(fd);
exit(0);
} else {
// father
pid_t pid;
...
The producer process:
void producer(int *fd) {
char buff[BUFFSIZE];
char *line;
close(fd[0]);
while (1) {
fflush(stdout);
fprintf(stdout, "Insert string:\t");
scanf("%[^\n]s%*c", buff);
fflush(stdout);
line = strdup(buff);
printToPipe(fd[1], line);
if (!strcmp(line, "end")) // Special string terminates process
return;
sleep(1);
}
return;
}
And the consumer process:
void consumer(int *fd) {
char *buff;
close(fd[1]);
while (1) {
if ( (buff = readFromPipe(fd[0])) == NULL ) {
close(fd[0]);
return;
}
fprintf(stdout, "%s\n", strToUpper(buff));
fflush(stdout);
}
return;
}
The printToPipe() and readfromPipe() directly implement the read() and write() system calls.
Unexpected behaviour:
Once the first phrase is typed in and converted to upper case the program goes on an infinite loop printing out the prompt and the first uppercase phrase (i.e.: Insert string: TEST TEST
). In particular:
- subsequent scanfs are ignored despite me accounting for the \n character (
scanf("%[^\n]s%*c", buff);
). If i check for the scanf return value it is 0 for all iterations following the 1st one, - it seems like conusmer "self sustains" itself with it's output: it doesn't wait for new input through the pipe and keeps printing the transformed phrase.