【发布时间】:2016-09-16 18:20:49
【问题描述】:
我正在尝试使用管道将数据从父级传递给子级。但是父进程在子进程执行之前就关闭了。
我正在提供代码,请告诉我哪里出错了。
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);
}
我得到的输出是这样的:
父 7432 的 PID
xyz@ubuntu:~/Desktop$ 子 4686 的 PID
收到的字符串:Canyoucanacan。
我不希望父进程在子进程执行结束之前关闭。
【问题讨论】: