intmain() { pid_t pid; //创建一个进程 pid = fork(); //创建失败 if (pid < 0) { perror("fork error:"); exit(1); } //子进程 if (pid == 0) { printf("I am the child process.\n"); //输出进程ID和父进程ID printf("pid: %d\tppid:%d\n",getpid(),getppid()); printf("I will sleep five seconds.\n"); //睡眠5s,保证父进程先退出 sleep(5); printf("pid: %d\tppid:%d\n",getpid(),getppid()); printf("child process is exited.\n"); } //父进程 else { printf("I am father process.\n"); //父进程睡眠1s,保证子进程输出进程id sleep(1); printf("father process is exited.\n"); } return0; }
运行结果:
1 2 3 4 5 6 7 8 9
# g++ a.cpp -o a.out # ./a.out I am father process. I am the child process. pid: 371 ppid:370 I will sleep five seconds. father process is exited. pid: 371 ppid:1 child process is exited.
intmain() { pid_t pid; pid = fork(); if (pid < 0) { perror("fork error:"); exit(1); } elseif (pid == 0) { printf("I am child process.I am exiting.\n"); exit(0); } printf("I am father process.I will sleep two seconds\n"); //等待子进程先退出 sleep(2); //输出进程信息 system("ps -o pid,ppid,state,tty,command"); printf("father process is exiting.\n"); return0; }
运行结果:
1 2 3 4 5 6 7 8 9
I am father process.I will sleep two seconds I am child process.I am exiting. PID PPID S TT COMMAND 273 238 S pts/3 -bash 409 273 S pts/3 ./a.out 410 409 Z pts/3 [a.out] <defunct> 411 409 S pts/3 sh -c ps -o pid,ppid,state,tty,command 412 411 R pts/3 ps -o pid,ppid,state,tty,command father process is exiting.