linux下的C语言开发(进程创建及等待)
2015-10-15 14:36
531 查看
在Linux下面,创建进程是一件十分有意思的事情。我们都知道,进程是操作系统下面享有资源的基本单位。那么,在Linux下面应该怎么创建进程呢?其实非常简单,一个fork函数就可以搞定了。但是,我们需要清楚的是子进程与父进程之间除了代码是共享的之外,堆栈数据和全局数据均是独立的。
[cpp] view
plaincopy
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
if(-1 == (pid = fork()))
{
printf("Error happened in fork function!\n");
return 0;
}
if(0 == pid)
{
printf("This is child process: %d\n", getpid());
}
else
{
printf("This is parent process: %d\n", getpid());
}
return 0;
}
所谓进程等待,其实很简单。前面我们说过可以用fork创建子进程,那么这里我们就可以使用wait函数让父进程等待子进程运行结束后才开始运行。注意,为了证明父进程确实是等待子进程运行结束后才继续运行的,我们使用了sleep函数。但是,在linux下面,sleep函数的参数是秒,而windows下面sleep的函数参数是毫秒。
[cpp] view
plaincopy
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
pid_t pid;
if(-1 == (pid = fork()))
{
printf("Error happened in fork function!\n");
return 0;
}
if(0 == pid)
{
printf("This is child process, %d\n", getpid());
sleep(5);
}
else
{
wait(NULL);
printf("This is parent process, %d\n", getpid());
}
return 1;
}
下面,我们需要做的就是两步,首先输入gcc fork.c -o fork, 然后输入./fork,就会在console下面获得这样的结果。
[cpp] view
plaincopy
[root@localhost fork]# ./fork
This is child process, 2135
This is parent process, 2134
[cpp] view
plaincopy
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
if(-1 == (pid = fork()))
{
printf("Error happened in fork function!\n");
return 0;
}
if(0 == pid)
{
printf("This is child process: %d\n", getpid());
}
else
{
printf("This is parent process: %d\n", getpid());
}
return 0;
}
所谓进程等待,其实很简单。前面我们说过可以用fork创建子进程,那么这里我们就可以使用wait函数让父进程等待子进程运行结束后才开始运行。注意,为了证明父进程确实是等待子进程运行结束后才继续运行的,我们使用了sleep函数。但是,在linux下面,sleep函数的参数是秒,而windows下面sleep的函数参数是毫秒。
[cpp] view
plaincopy
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
pid_t pid;
if(-1 == (pid = fork()))
{
printf("Error happened in fork function!\n");
return 0;
}
if(0 == pid)
{
printf("This is child process, %d\n", getpid());
sleep(5);
}
else
{
wait(NULL);
printf("This is parent process, %d\n", getpid());
}
return 1;
}
下面,我们需要做的就是两步,首先输入gcc fork.c -o fork, 然后输入./fork,就会在console下面获得这样的结果。
[cpp] view
plaincopy
[root@localhost fork]# ./fork
This is child process, 2135
This is parent process, 2134
相关文章推荐
- linux下的C语言开发(自动编译工具)
- Linux系统之热插拨事件uevent
- linux下的C语言开发(定时器)
- linux下的C语言开发(动态库) 转载加原创
- linux下的C语言开发(静态库) 转载加原创
- linux下的C语言开发(gdb调试)
- linux下的C语言开发(makefile编写)
- Linux命令TR
- linux下的C语言开发(开篇)
- Android源码编译及替换成自己编译的linux内核
- linux 下配置 MAVEN
- Linux文件权限
- linux下面的df命令
- Linux进程实践(2) --僵尸进程与文件共享
- linux文件类型
- Linux 中 CURL常用命令详解
- linux下面的挂载点讲解
- Linux Frame Buffer 驱动
- 14行脚本配置Linux下一个Java环境变量
- Linux学习 -- 日志管理