- 论坛徽章:
- 0
|
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/uio.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
#include<sys/wait.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
char buf[100]={0};
pid_t cld_pid;
int fd;
int status;
if((fd=open("temp",O_CREAT|O_RDWR|O_TRUNC,0664))==-1){
perror("创建失败");
exit(1);
}
strcpy(buf,"父进程数据");
if((cld_pid=fork())==0){
strcpy(buf,"子进程数据");
puts("子进程正在工作:");
printf("子进程PID是:%d\n",getpid());
printf("父进程PID是:%d\n",getppid());
write(fd,buf,strlen(buf));
close(fd);
exit(0);
}
else{
puts("父进程正在工作:");
printf("父进程PID是%d:\n",getpid());
printf("子进程PID是%d:\n",cld_pid);
write(fd,buf,strlen(buf));
close(fd);
}
wait(&status);
return 0;
}
执行后,终端显示:
父进程正在工作:
父进程PID是3464:
子进程PID是3465:
子进程正在工作:
子进程PID是:3465
父进程PID是:3464
temp文件内容为:
父进程数据子进程数据
有几个地方不明白。
1.明明用了if else 为什么if条件成立与不成立的内容都会输出。
2.为什么先输出的是ELSE的内容 if条件明明是成立的。
有点似懂非懂的感觉,有点矛盾,这个程序中父进程应该就是程序本身把,调用FORK()创建子进程。子进程执行了,问题就是else中的内容是什么时间执行的,这点真的很不明白。按照输入的内容来看,else的内容是父进程的,先执行父进程,输出父进程的内容,然后调用子进程,输出子进程的内容,似乎是这样。但是明明有if else else的内容到底为什么会执行。。
既然if成立的内容执行了,else应该是绝对不会执行的才对呀。这里很不明白。
求解答呀,纠结死了。
|
|