在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;
- }
-
|