在Linux下面,创建进程是一件十分有意思的事情。我们都知道,进程是操作系统下面享有资源的基本单位。那么,在Linux下面应该怎么创建进程呢?其实非常简单,一个fork函数就可以搞定了。但是,我们需要清楚的是子进程与父进程之间除了代码是共享的之外,堆栈数据和全局数据均是独立的。
- #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的函数参数是毫秒。
- #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;
- }
- [root@localhost fork]# ./fork
- This is child process, 2135
- This is parent process, 2134