Hello there,
I'm new to C programming and am following a course in C.
I've got an example code for piping. It's not a very hard code to understand. It goes like this:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define READ_END 0
#define WRITE_END 1
const char banner [] = "hello there\n";
int main()
{
int pipe_ends[2];
pid_t pid;
if(pipe(pipe_ends)) {
printf("Could not create pipe\n");
return -1;
}
pid = fork();
if(pid < 0) {
printf("Fork failed\n");
return -1;
}
if(pid > 0) { /* parent */
int i;
close(pipe_ends[READ_END]);
for(i=0; i<10; i++) {
printf("Parent Writing [%d]...\n",i);
write(pipe_ends[WRITE_END], banner, strlen(banner));
}
exit(EXIT_SUCCESS);
}
if(pid == 0) { /* child */
char buff[128];
int count;
int x = 0;
close(pipe_ends[WRITE_END]);
while((count = read(pipe_ends[READ_END], buff, 128)) > 0) {
write(STDOUT_FILENO, &buff, count);
sleep(1);
}
}
return 0;
}
Now my problem is not with the pipes. But when you run this, the program never ends!!! I experimented adding few prinf lines and found out that the child reaches the last code (i.e. the return 0 line) but it seems never to exit. Why is this?
I'm really new to C and please excuse me if I'm asking you something really stupid. Please help me.