I was practicing pipes in system programming when i realized that my program isn’t exiting. I added exit() in both child and parent, but the child still isn’t exiting. Please help…
Here is the code:
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
//#include "apue.h"
main() {
int n,max=20;
pid_t pid;
int fd[2];
char line[max];
int i;
for(i=0;i<20;i++) {
line[i]='\0';
}
if(pipe(fd)<0) {
perror("pipe error");
}
if((pid=fork())<0) {
perror("fork error");
}
else if(pid > 0) {
close(fd[0]);
write(fd[1], "hello world\n", 12);
exit(1);
} else {
close(fd[1]);
read(fd[0], line, max);
}
puts(line);
exit(1);
}
First of all, fork returns 0 in the child not in the parrent. So, when you write
You are in the parrent process. To be in the child process space, you shoud use
else if(pid **==** 0)The seccond thing you should do to make sure everything works fine, you should not call in the child process code space the function
exit(). You would better wait your child process in the parrent process. For this you should use thewait()function in the parrent process.The good code would be:
}