#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
int glob = 6;
char buf[] = "a write to stdout\n";
int main()
{
int var;
pid_t pid;
var = 88;
fprintf(stderr, "%s", buf);
printf("before fork\n");
pid=fork();
printf("after fork\n");
if(pid < 0 )
{
fprintf(stderr, "fork error\n");
}
else if(pid == 0)
{
glob++;
var++;
printf("child process\n");
printf("pid = %d, father pid = %d, glob = %d, var = %d\n", getpid(), getppid(), glob, var);
exit(0);
}
else
{
//exit(0);
//sleep(2);
printf("father process\n");
printf("pid = %d, father pid = %d, glob = %d, var = %d and child id is %d\n", getpid(), getppid(), glob, var,pid);
}
return 0;
}
执行后的输出如下:
[root@localhost fork]# gcc -o fork fork.c
[root@localhost fork]# ./fork
a write to stdout
before fork
after fork
father process
pid = 23834, father pid = 18743, glob = 6, var = 88 and child id is 23835
[root@localhost fork]# after fork
child process
pid = 23835, father pid = 1, glob = 7, var = 89
tips:
被fork创建的新进程叫做自进程。fork函数被调用一次,却两次返回。返回值唯一的区别是在子进程中返回0,而在父进程中返回子进程的pid。在父进程中要返回子进程的pid的原因是父进程可能有不止一个子进程,而一个进程又没有任何函数可以得到他的子进程的pid。
子进程和父进程都执行在fork函数调用之后的代码,子进程是父进程的一个拷贝。例如,父进程的数
据空间、堆栈空间都会给子进程一个拷贝,而不是共享这些内存。
没有评论:
发表评论