搞清楚fork()子进程是父进程地址空间的副本,所以不能妄想通过全局变量控制子进程。IPC
而vfork()是子进程在父进程地址空间运行且子进程优先执行。
实例验证:
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<iostream>
using namespace std;
void fun(char *ptr);
int flag=false;
int
main()
{
pid_t pid;
if((pid=fork())<0)
cout<<"fork error"<<endl;
else if(pid==0)//child process
{
while(flag==false);//polling
fun("output from child process");
exit(0);
}
else if(pid>0)
{
fun("output from parent process");
flag=true;
}
if(wait(0)<0)
cout<<"wait error"<<endl;
return 0;
}
void fun(char* ptr)
{
char *p;
int c;
setbuf(stdout,NULL);
for(p=ptr;(c=*p++)!=0;)
putc(c,stdout);
cout<<endl;
}
输出结果:
output from parent process
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<iostream>
using namespace std;
void fun(char *ptr);
int flag=false;
int
main()
{
pid_t pid;
if((pid=vfork())<0)
cout<<"fork error"<<endl;
else if(pid==0)//child process
{
flag=true;
//while(flag==false);//polling
fun("output from child process");
exit(0);
}
else if(pid>0)
{
fun("output from parent process");
}
//if(wait(0)<0)
// cout<<"wait error"<<endl;
cout<<flag<<endl;
return 0;
}
void fun(char* ptr)
{
char *p;
int c;
setbuf(stdout,NULL);
for(p=ptr;(c=*p++)!=0;)
putc(c,stdout);
cout<<endl;
}
输出结果:
output from child process
output from parent process
1