Re: c++ 练习源码,fock
发表于 : 2024-11-30 13:58
代码: 全选
#include <stdio.h>
#include <unistd.h>
int main(){
pid_t fpid; //fpid表示fork函数返回的值
int count = 0;
fpid = fork();
if (fpid < 0){
printf("error in fork!");
}else if (fpid == 0) {
printf("I am the child process, my process id is %d\n", getpid());
printf("我是爹的儿子\n");
count++;
}else {
printf("I am the parent process, my process id is %d\n", getpid());
printf("我是孩子他爹\n");
count++;
}
printf("统计结果是: %d\n", count);
int i = 0;
printf("i child/parent ppid pid fpid\n");
//ppid指当前进程的父进程pid
//pid指当前进程的pid,
//fpid指fork返回给当前进程的值
for (i = 0; i<2; i++){
pid_t fpid = fork();
if (fpid == 0)
printf("%d child %4d %4d %4d\n", i, getppid(), getpid(), fpid);
else
printf("%d parent %4d %4d %4d\n", i, getppid(), getpid(), fpid);
}
return 0;
}