设为首页 加入收藏

TOP

关于Linux操作系统Fork的使用
2011-06-02 19:52:50 来源: 作者: 【 】 浏览:560次 评论:0

Fork创建一个新的进程,新创建的进程是子进程,它是对父进程以后代码的一个复制,通常用来做多进程的服务器,也可以在子进程中运行独立的代码。

用getpid可以判断当前是子进程还是父进程。

看下面这个例子:

以下为引用的内容:

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid;
static int n = 0;
printf("fork!\n");
switch (pid = fork())
{
case -1:
{
/* ..pid.-1.fork.... */
/* ........ */
/* .......... */
perror("The fork failed!");
break;
}
case 0:
{
/* pid.0.... */
printf("[child]i am child!\n");
printf("[child]getpid=[%d]\n", getpid() );
printf("[child]pid=[%d]\n", pid );
break;
}
default:
{
/* pid..0.... */
printf("[parent]i am parent!\n" );
printf("[parent]getpid=[%d]\n",getpid() );
printf("[parent]pid=[%d]\n",pid );
break;
}
}
printf("n=[%d]\n", n++);

return 0;
}

这个例子在linux下用gcc编译,运行结果如下:

以下为引用的内容:

fork!
[child]i am child!
[child]getpid=[7422]
[child]pid=[0]
n=[0]
[parent]i am parent!
[parent]getpid=[7421]
[parent]pid=[7422]
n=[0]

您看到此篇文章时的感受是:
Tags: 责任编辑:administrator
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到QQ空间
分享到: 
上一篇Apache的基本设置和乱码解决方法 下一篇ChartDirector Linux下中文显示问..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

相关栏目

最新文章

图片主题

热门文章

推荐文章

相关文章

广告位