源代码:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main(int arg, char **argc)
{
pid_t childPID = 0;
int ret = 0;
int x = 0;
x++;
printf("PID=%d, PPID=%d x=%d\n", getpid(), getppid(), x);
ret = fork();
if (ret == -1) {
printf("failed to create child process\n");
exit(0);
} else if (ret == 0) { /* 这是在子进程里 */
printf("PID=%d, PPID=%d child-created OK, ret=%d\n", getpid(),
getppid(), ret);
x = x + 5;
printf("child-x=%d\n", x);
sleep(5);
printf("child-x=%d\n", x);
sleep(5);
} else { /* 这是在父进程里 */
childPID = ret;
printf("PID=%d, PPID=%d parent-created OK, child PID=%d\n",
getpid(), getppid(), childPID);
printf("parent-x=%d\n", x);
sleep(15);
x = x + 10;
printf("parent-x=%d\n", x);
}
printf("PID=%d, PPID=%d Last:x=%d\n", getpid(), getppid(), x);
return 0;
}
编译:gcc fork.c -Wall
运行:. /a.out
结果:
PID=14858, PPID=6194 x=1
PID=14859, PPID=14858 child-created OK, ret=0
child-x=6
PID=14858, PPID=6194 parent-created OK, child PID=14859
parent-x=1
child-x=6
PID=14859, PPID=14858 Last:x=6
parent-x=11
PID=14858, PPID=6194 Last:x=11
--
/**************************************/
Name: Xiong Feng
E-mail:linux0818@gmail.com
MSN:linux0818@hotmail.com
QQ:23562033
Address: GuangZhou.China
/**************************************/
没有评论:
发表评论