eyesmore 发表于 2013-2-5 02:36:06

fork 创建子进程

fork 创建子进程,特点: 调用一次,返回两次。
 
#include<stdio.h>int main(char** args) {   int cpid = fork();if(cpid == 0) {   //in the child process   printf("I am child process, PID= %d, cpid = %d \n",getpid(),cpid);}   else if(cpid > 0) {   //in the parent process    printf("I am parent process, PID= %d, cpid = %d \n",getpid(),cpid);}else {   //unable to create child process   perror("unable to create child");} } 
/*
int r = fork()
如果返回0,则表示进入子进程代码逻辑;
如果返回正数,该正数等于子进程的进程号,并执行父进程的后继逻辑;
如果返回负数,则表示子进程创建失败,数值表示失败的原因。
调用一次,返回两次,至于先返回子进程,还是返回父进程是不可预知的。
*/
 
编译并运行
bash-3.00$ gcc -o forkdemo.o forkdemo.c
bash-3.00$ forkdemo.o
I am parent process, PID= 1667082, cpid = 839764
I am child process, PID= 839764, cpid = 0
bash-3.00$ ls
forkdemo.c  forkdemo.o  lib.c       lib.o       main.c      main.o      myHello     tags
bash-3.00$
页: [1]
查看完整版本: fork 创建子进程