Reputation: 2122
HI I am trying to pass integers from 0-9 to my child process one at a time. Inside the child process I will simply print the integer. Is that even possible? Here is what I have as draft so far and it only prints the first 0.
if (pid >0){
/*abusive parents*/
if((close(fd[0])) == -1){
perror("close:");}
int k;
for (k=0;k<10;k++){
write(fd[1], &k, sizeof(int));
}
close(fd[1]);
}
else if(pid ==0){
/*stupid child*/
int k;
if((close(fd[1])) == -1){
perror("close:");}
read(fd[0],&k,sizeof(int));
printf("k in child is %d\n",k);
close(fd[0]);
}
Upvotes: 0
Views: 955
Reputation: 12715
EDIT: Following works
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int fd[2];
pipe(fd);
int pid = fork();
if (pid >0){
/*abusive parents*/
if((close(fd[0])) == -1){
perror("close:");}
int k;
for (k=0;k<10;k++){
write(fd[1], &k, sizeof(int));
}
close(fd[1]);
}
else if(pid ==0){
/*stupid child*/
int i,k;
if((close(fd[1])) == -1){
perror("close:");}
for (i=0;i<10;i++) {
read(fd[0],&k,sizeof(int));
printf("k in child is %d\n",k);
}
close(fd[0]);
}
return 0;
}
Output:
k in child is 0
k in child is 1
k in child is 2
k in child is 3
k in child is 4
k in child is 5
k in child is 6
k in child is 7
k in child is 8
k in child is 9
Upvotes: 2