1. 有如下的程序:
#include
main( )
{
pid_t pid;
pid = fork();
if(!pid)
printf("this is child,my pid is %d\n",getpid());
else if (pid>0)
printf("this is parent,child has pid %d, and my pid is %d\n ",pid,getpid());
else
printf("fork fail\n ");
}
编译运行后得到如下结果:
this is child, my pid is 3845
this is parent, child has pid 3845, and my pid is 3844.
试解释产生上述结果的原因,并分析程序的执行过程。
答案:
1. 原因:程序输出的两行是来自两个进程,是同一个程序的两次执行。
2. 程序的执行过程:主函数首先定义了一个pid_t类型的变量,然后执行到语句pid=fork()一个与父进程相同的共享代码空间fork处继续执行,相互竞争系统的资源。
3. fork之后子进程除非采用了同步手段,否则不能确定谁先运行,也不能确定谁先结束。子进程中fork调用返回0返回子进程的#include
#include
int main()
{
pid_t result;
int var=10;
printf("before fork,var=%d\n",var);
result=fork();
if(result<0)
printf("fork fail\n");
else if(result>0)
{
var++;
printf("This is parent!\n”);
}
else
{
var- -;
printf("This is child!\n");
}
printf("after fork var=%d\n",var);
return 0;
}
假定父子进程均可在一个时间片内执行完,且操作系统每次均先调度子进程。
答案:
程序的执行结果为
before fork,var=10
This is child
after fork var=9
before fork,var=10
This is parent!
after fork var=11
程序的执行过程如下:
1. 程序先定义了两个变量result和var,然后输出变量var的值,得到"before fork var=10"这一行输出(父子进程各复制了一份)。
2. 当执行到result=fork()时程序分叉,产生父子两个进程。
3. 系统首先调度子进程执行,直至子进程结束。(题目假定父子进程均可在一个时间片内执行完,且操作系统每次均先调度子进程。)而在子进程中result为0,故执行的是条件分支的最后一个分支,输出:
This is child.
after fork var=9
4. 子进程执行完了之后调度父进程执行,直至父进程结束。而在父进程中result为子进程号,大于0,于是执行条件分支的第二个个分支,输出:
This is parent
after fork var=11
3. 分析下列程序,(1)写出执行结果(2)多次执行,每次的执行结果是否相同,分析其原因
#include”stdio.h”
#include/*提供类型pid_t的定义*/
#include
void main()
{
pid_t id=0;
char *parameter[3];
parameter[0]=”ls”
parameter[1]=”-1”
parameter[2]=0;
printf(“***About to exec ls -1\n”);
printf(“***AAAAAAAAA*****\n”);
id=fork();
if(id==0)
{
execvp(“ls”, parameter);
}
else
{
wait(NULL);
printf(“***ls is done.bye\n”);
printf(“***BBBBBBBBBB\n”);
}
}
答案:
***About to exec ls –l
***AAAAAAAAA*****
文件夹内容列表
***ls is done.bye
***BBBBBBBBBB*****
执行结果相同,原因是f