进程创建fork
#include <sys/types.h>
#include <unistd.h>
pid_t fork(viod)
返回值:,在子进程中返回0;在父进程中返回大于0的进程号;小于0,出错。
fork()函数调用一次,返回两次,分别是在子进程和父进程中。
演示:
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>int main(void)
{pid_t pid;pid = fork();if (pid < 0) {printf("get pid error.\n");}if (pid > 0) {printf("this is parent process, pid: %d, ppid: %d, fork return id: %d\n", getpid(), getppid(), pid);} else {printf("this is child process, pid: %d, ppid: %d, fork return id: %d\n", getpid(), getppid(), pid);}printf("pid: %d.\n",getpid());sleep(1);return 0;
}
运行结果:
root@spark# ./fork
this is parent process, pid: 32128, ppid: 32092, fork return id: 32129
pid: 32128.
this is child process, pid: 32129, ppid: 32128, fork return id: 0
pid: 32129.
root@spark#