- 论坛徽章:
- 0
|
在编写socket ftp之前,我对fork函数进行了学习。
先看这段范例代码:
![]()
#include unistd.h>;
![]()
![]()
![]()
#include sys/types.h>;
![]()
![]()
![]()
main ()
![]()
![]()
![]()
![]()
![]()
{
![]()
![]()
![]()
pid_t pid;
![]()
![]()
![]()
pid=fork();
![]()
![]()
![]()
if (pid 0)
![]()
![]()
![]()
printf("error in fork!");
![]()
![]()
![]()
else if (pid == 0)
![]()
![]()
![]()
printf("i am the child process, my process id is %dn",getpid());
![]()
![]()
![]()
else
![]()
![]()
![]()
printf("i am the parent process, my process id is %dn",getpid());
![]()
![]()
![]()
![]()
}
![]()
这段代码写了一个使用fork函数创建子进程,父子进程同时运行而产生交错的,不一样的运行结果。
运行结果如下:
[root@localhost c]# ./a.out
i am the child process, my process id is 4286
i am the parent process, my process id is 4285
fork在英文中是叉子,分叉的意思,在函数fork中,取后面的意思。很形象的表示程序从这里分叉,fork函数创建了子进程,子进程和父进程同时(其实是cpu分时处理)开始运行分叉之后的程序。
我把程序改写了一下:
![]()
#include unistd.h>
![]()
#include sys/types.h>
![]()
main()
![]()
![]()
![]()
{
![]()
pid_t pid;
![]()
printf("\n[%d]not fork pid=%d\n",getpid(),pid);
![]()
pid=fork();
![]()
printf("\n[%d]forked pid=%d\n",getpid(),pid);
![]()
if(pid0)
![]()
![]()
![]()
{
![]()
printf("error in fork!\n");
![]()
getchar();
![]()
exit(1);
![]()
}
![]()
else if(pid==0)
![]()
printf("\n[%d]in child process,p_id=%d\n",getpid(),getpid());
![]()
else
![]()
![]()
![]()
{
![]()
printf("\n[%d]in parent process,my pid=%d\n",getpid(),pid);
![]()
printf("\n[%d]in parent process,my getpid=%d\n",getpid(),getpid());
![]()
![]()
}
![]()
}
![]()
程序运行结果如下:
[hardy@localhost fork]$ ./fork
[3819]not fork
[3820]forked pid=0
[3820]in child process,p_id=3820
[3819]forked pid=3820
[3819]in parent process,my pid=3820
[3819]in parent process,my getpid=3819
可以清楚的看到 not fork只打印了一次,其中[3819]是父进程的进程号,创建fork以后,fork函数返回给父进程的值pid是子进程的进程号[3820],而在子进程中,pid值为零。也就是说子进程中,pid被置零。
引用网上一位网友的解释“其实就相当于链表,进程形成了链表,父进程pid(p 意味point)指向子进程的进程id, 因为子进程没有子进程,所以其pid为0. ”
下面有一个很有意思的程序:
![]()
#include sys/types.h>
![]()
#include unistd.h>
![]()
![]()
int main()
![]()
![]()
![]()
{
![]()
int i;
![]()
for( i= 0; i 3; i++)
![]()
![]()
<SPAN id=Codehighlighter1_110_361_Closed_Text style="BORDER-RIGHT: #808080 1px solid; BORDER-TOP: #808080 1px solid; DIS
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/101900/showart_2020076.html |
|