1.使用fork函数创建一个进程
#include <unistd.h>pid_t fork(void);
返回值为0,代表当前进程是子进程
返回值为非负数,代表当前进程为父进程
调用失败,返回-1
代码:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>int main()
{pid_t pid;pid = getpid();printf("pid=%d,getpid=%d\n",pid,getpid());int fd = fork();if(fd==0){printf("son process is pid=%d,getpid=%d\n",pid,getpid());}else if(fd>0){printf("father process is pid=%d,getpid=%d\n",pid,getpid());}else if(fd<0){puts("ERRO");exit(-1);}return 0;
}
运行结果:
fork原理: