小弟在学习LINUX程序设计时遇到有关wait和waitpid的问题,请各位达人帮忙,不胜感激。
我写了一个简单的小程序,用fork复制当前进程,然后让子进程创建一个文件(文件名:a,权限:755),然后向这个文件中写入一些数据。当子进程执行完毕以后,父进程打开并读取该文件,并且将读出的数据输出到屏幕上。可是,为什么父进程永远执行而不停止呢?(即不停地输出数据,而实际上数据只有十行)小弟百思不得其解,望高手指点。(环境:REDHAT LINUX 9,GCC3.2.2)
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/wait.h>
int main()
{
#ifdef DEBUG
printf("Program started\n");
#endif
pid_t child;
pid_t childpid;
int fd,fd2;
int ret;
int i;
int length;
int status;
char data[] = "This is for test\n";
char *buf;
length = strlen(data);
printf("Process ID: %ld\n", (long)getpid());
printf("Parent Process ID: %ld\n", (long)getppid());
child = fork();
childpid = wait(NULL);
fprintf(stderr,"Waiting for child pid = %ld\n",(long)childpid);
if(child == -1)
{
perror("Process duplication error\n");
return -1;
}
if(child == 0)
{
fprintf(stderr,"child pid = %ld\n",(long)getpid());
fd = open("a",O_CREAT | O_RDWR,0755);
if(fd < 0)
{
perror("File creation error");
return -1;
}
for(i = 0;i < 10; i++)
{
ret = write(fd, data,length);
if(ret < 0)
{
perror("Write data error");
return -1;
}
}
close(fd);
}
else
{
//waitpid(-1,&status,WNOHANG);
fd2 = open("a",O_RDONLY);
if(fd2 < 0)
{
perror("File a open error");
return -1;
}
while((read(fd2,buf,length) != -1))
{
fprintf(stderr,"%s\n",buf);
}
close(fd2);
}
#ifdef DEBUG
printf("Parent Process Came to Here\n");
#endif
return 0;
}