您的位置:首页 > 运维架构 > Linux

linux学习笔记:关于多级fork后的scanf输入的疑惑

2010-08-09 21:33 337 查看
上一篇说道关于守护进程的通信问题,我有一个想法,就是多级fork出子进程,然后这些子进程间来通信,代码就可以缩减到一个文件里了。但是实践了下发现行不通,不是通信不行,是scanf这个函数无法正确读取。下面来几段代码看下:

1.

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
int main(int argc,char *argv[]){
if(fork()>0){
int m;
scanf("%d",&m);
printf("%d/n",m);


}else{

}

return 0;
}


在fork后的父进程里scanf,运行正常。



2。

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
int main(int argc,char *argv[]){
if(fork()>0){


exit(0);

}else{


int m;
scanf("%d",&m);
printf("%d/n",m);


}

return 0;
}


fork后在子进程里scanf,父进程直接退出,发现scanf读入错误。



3。

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<sys/wait.h>
int main(int argc,char *argv[]){
if(fork()>0){
wait(0);
}else{
int m;
scanf("%d",&m);
printf("%d/n",m);


}

return 0;
}


在父进程里wait阻塞,子进程scanf,发现运行正常。



4。

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<sys/wait.h>
int main(int argc,char *argv[]){
if(fork()>0){
wait(0);
}else{
if(fork()>0){
wait(0);
}else{
int m;
scanf("%d",&m);
printf("%d/n",m);
}
}


return 0;
}
在子进程里在fork出孙进程,上面的这段代码运行正常的,但是如果把子进程的wait函数去掉,scanf的读入就出错了。




好了,不举例子了,免得弄糊涂了,总结下,也就是说当我们想在fork后的子进程里让scanf正确读入时,它的这个进程组的发起进程(领头进程)必须处于wait状态(不谈init进程)。

文章有不妥之处,还望大家多多指正。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: