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

       上一篇说道关于守护进程的通信问题,我有一个想法,就是多级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进程)。

       文章有不妥之处,还望大家多多指正。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值