I have a C program where the father process creates two children processes: the first child needs to read from an existing text file, and using execlp("cut","cut", options...) it needs to extract the second word from each line in the text file and write it on a pipe. The other process then needs to read each line (1 word per line) from the pipe and print something to stdout for every line. The issue being, when reading from pipe I get an additional blank line at the end which messes up the lines count. I think the execlp created that additional line, because when I run the same command from the terminal, it seems to work fine. Because of this the second child can't terminate and the program doesn't terminate normally. Why could this additional line be?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
void wait_child() {
int terminated, status;
terminated=wait(&status);
if (WIFEXITED(status)) {
printf("Child termination ok\n");
}else if (WIFSIGNALED(status)) {
printf("Child termination not ok\n");
}
}
void child1(int ppwrite, char* file) {
int fd, nread;
char buffer;
char *f="-f2"; //i want the second word in each line
char *d="-d " "";
dup2(ppwrite,1); //output to pipe
close(ppwrite);
execlp("cut","cut", d,f,file,(char*)0); //Why does it write an additional blank line?
perror("exec error\n");
}
void child2(int ppread) { //i want this to print: "Line X: word" for each line in pipe
int nread,nlines;
char buffer;
nlines=0;
printf("Line 1: ");
while ((nread=read(ppread, &buffer, sizeof(buffer)))>0) {
if (buffer=='\n') {
nlines++;
printf("\nLine %d: ", nlines+1);
} else {
printf("%c", buffer);
}
// printf("%d", nlines); //here I notice that it reads an additional not wanted char
}
close(ppread);
}
void handler(int signum) {
if (signum==SIGALRM) {
printf("Timeout\n");
exit(EXIT_SUCCESS);
}
}
int main(int argc, char* argv[]) {
int pid1,pid2;
int pp[2];
if (pipe(pp)<0) {
printf("Errore creazione pipe\n");
exit(EXIT_FAILURE);
}
signal(SIGALRM, handler);
alarm(5);
pid1=fork();
if (pid1<0) {
printf("P1 could not be created\n");
exit(EXIT_FAILURE);
} else if (pid1==0) {
close(pp[0]);
child1(pp[1], "myfile.txt");
} else {
pid2=fork();
if (pid2<0) {
printf("P2 could not be created\n");
exit(EXIT_FAILURE);
} else if (pid2==0) {
close(pp[1]);
child2(pp[0]);
} else {
for (int i=0; i<2; i++) {
wait_child();
}
}
}
}```