Reputation: 23
I am trying to pass data from parent to child using pipe. But the parent process is getting closed before the child process gets executed.
I am providing the code please let me know where I am getting wrong.
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[50];
char readbuffer[100];
FILE *fp;
pipe(fd);
char var[100];
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid != 0)
{
printf("PID of parent %u\n",getpid());
/* Child process closes up input side of pipe */
close(fd[0]);
fp = fopen("test.txt","r");
//scanning from file
while(fscanf(fp,"%s\n",string)!=EOF)
{
strcat(var,string);
}
//printf("%s",string);
/* Send "string" through the output side of pipe */
write(fd[1], var, (strlen(var)+1));
close(fd[1]);
// exit(0);
}
else
{
printf("PID of child %u\n",getppid());
/* Parent process closes up output side of pipe */
close(fd[1]);
//open a file
//fp = fopen("test.txt","r");
//scanning from file
//fscanf(fp,"%s\n",string);
//printf("%s",string);
//printinf from file
//fprintf(fp,string);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
//exit(0);
close(fd[0]);
}
return(0);
}
and the output I am getting is like this:
PID of parent 7432
xyz@ubuntu:~/Desktop$ PID of child 4686
Received string: Canyoucanacan.
I do not want the parent process to close before the child process execution is over.
Upvotes: 1
Views: 4038
Reputation: 33601
In the parent, you must wait for the child to complete with waitpid
[or equivalent].
So, the last line of the parent part of the if/else
should be:
waitpid(childpid,NULL,0);
Here's the updated code showing placement:
int
main(void)
{
int fd[2],
nbytes;
pid_t childpid;
char string[50];
char readbuffer[100];
FILE *fp;
pipe(fd);
char var[100];
if ((childpid = fork()) == -1) {
perror("fork");
exit(1);
}
if (childpid != 0) {
printf("PID of parent %u\n", getpid());
/* Child process closes up input side of pipe */
close(fd[0]);
fp = fopen("test.txt", "r");
// scanning from file
while (fscanf(fp, "%s\n", string) != EOF) {
strcat(var, string);
}
// printf("%s",string);
/* Send "string" through the output side of pipe */
write(fd[1], var, (strlen(var) + 1));
close(fd[1]);
// exit(0);
#if 1
waitpid(childpid,NULL,0);
#endif
}
else {
printf("PID of child %u\n", getppid());
/* Parent process closes up output side of pipe */
close(fd[1]);
// open a file
// fp = fopen("test.txt","r");
// scanning from file
// fscanf(fp,"%s\n",string);
// printf("%s",string);
// printinf from file
// fprintf(fp,string);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
// exit(0);
close(fd[0]);
}
return (0);
}
Upvotes: 1