使用文件IO 实现父进程向子进程发送信息,并总结中间可能出现的各种问题
运行结果:
出现问题:
1、由于无法控制子进程和父进程的时间片抢夺,所以导致读写混乱;
2、采用sleep来控制两者运行状态的话,会导致只能在代码设置的休眠时间段内进行输入消息,因此输入输出会有时间限制,两个进程都只能等待休眠期的结束在开始执行,操作大大受限;
3、以当前所学内容只能勉强实现效果,而无法对代码进行优,从而化达到要求的效果;
代码:
#include <allhead.h>
void My_write()
{
int dp=open("./mass.txt",O_WRONLY | O_CREAT | O_TRUNC,0664);
if(dp == -1)
{
perror("open:");
return ;
}
char buf[40]="0";
printf("父进程发送消息:");
gets(buf);
int res = write(dp,buf,strlen(buf));
if(res == -1)
{
perror("write:");
return ;
}
close(dp);
}
void My_read()
{
int dp2=open("./mass.txt",O_RDONLY);
if(dp2==-1)
{
perror("read:");
return ;
}
char buf1[40]="0";
int res1 = read(dp2,buf1,40);
if(res1==-1)
{
perror("read:");
return ;
}
printf("子进程收到消息:");
printf("%s\n",buf1);
close(dp2);
}
int main(int argc, const char *argv[])
{
int res2 = fork();
if(res2>0)
{
My_write();
sleep(5);
}
else if(res2==0)
{
sleep(5);
My_read();
}
else
{
perror("fork:");
return 1;
}
wait(NULL);
return 0;
}