i am trying to do simple read/write in pipe but it gives me error
this is my code :
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#define BUFSIZE 80
int main()
{
int fd[2],n,i,h;
char buf[BUFSIZE];
pipe(fd);
switch(fork())
{
case -1 :printf("Fork Error");
exit(0);
case 0 :close(fd[0]);
printf("Enter N :");
scanf("%d",&n);
write(fd[1],&n,sizeof(n));
close(fd[1]);
case 1 :close(fd[1]);
n=read(fd[0],&h,sizeof(h));
for(i=1;i<=h;i++)
{
if(i%2==1)
{
write(1,&i,n);
}
}
close(fd[0]);
}
exit(0);
}
in this code : child's fd[0] pointer is closed and write from child's fd[1] pointer and then parent reading from fd[1] pointer and stores it in h variable and then value of variable i is going in STDOUT_FILENO (1) and displays output on standard output
output :
kartik@ubuntu:~/Desktop/isp$
Enter N :6
6: command not found
There are several issues here:
N
in the child process, however the parent process is the one that receives input from the terminal. So by the time you enter "6", the parent process has exited and you're entering that value to the shell. Move the printf
and scanf
to before the fork
and you should be able to read that value properly.case 1
will not be entered for the case when fork()
returns from the parent, which seems to be your intent. fork()
returns the pid of the child to the parent. Because the special init
process has pid 1, this will never be true. Change case 1:
to default
to process the parent process.break
at the end of your switch cases. In C, switch cases "fall through", meaning that once the statement for one case are complete, it will continue running the statements for the following case. The break
statement at the end of each case prevents that from happening.With these corrections, you now have this:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#define BUFSIZE 80
int main()
{
int fd[2],n,i,h;
pid_t pid; // to capture the child pid
char buf[BUFSIZE];
// prompt for N before forking
printf("Enter N :");
scanf("%d",&n);
pipe(fd);
switch((pid=fork())) // saving the child pid in case we want to use it later
{
case -1 :
printf("Fork Error");
exit(0); // no break needed here because of exit
case 0 :
close(fd[0]);
write(fd[1],&n,sizeof(n));
close(fd[1]);
break; // end of case 0
default :
close(fd[1]);
n=read(fd[0],&h,sizeof(h));
printf("h=%d\n",h);
for(i=1;i<=h;i++)
{
if(i%2==1)
{
//write(1,&i,n);
printf("%d\n",i);
}
}
close(fd[0]);
break; // end of default case
}
exit(0);
}