#include <unistd.h> //unistd.h是unix std的意思,是POSIX标准定义的unix类系统定义符号常量的头文件
#include <sys/types.h> //是Unix/Linux系统的基本系统数据类型的头文件,含有size_t,time_t,pid_t等类型。
#include <sys/wait.h> //使用wait()和waitpid()函数时需要include这个头文件
#include <stdio.h> //是标准输入输出头文件
#include <stdlib.h> //stdlib 头文件即standard library标准库头文件,stdlib 头文件里包含了C、C++语言的最常用的系统函数
int main( void )
{
pid_t childpid; //定义一个子进程类型
//pid_t类似一个类型,就像int型一样,int型定义的变量都是整型的,pid_t定义的类型都是进程号类型
int status;
childpid = fork(); //fork( void )为创建子进程
if ( -1 == childpid ) // childpid的值只能 >=0
{
perror( "fork()" ); //基于errno的当前值,在标准出错上产生一条出错信息,然后返回
exit( EXIT_FAILURE );
}
else if ( 0 == childpid ) //childpid==0表示程序是在子进程中进行;若大于0,则是在父进程中进行
{
puts( "In child process" );
sleep( 3 ); //挂起进程指定的秒数,时间到了返回0
printf("\tchild pid = %d\n", getpid()); //函数返回值为当前进程的PID
printf("\tchild ppid = %d\n", getppid()); //返回父进程的PID
exit(EXIT_SUCCESS);
}
else //childpid >0 表示在父进程中进行
{
waitpid( childpid, &status, 0 ); //waitpid()会暂时停止目前进程的执行,直到有信号来到或子进程结束
puts( "in parent" );
printf( "\tparent pid = %d\n", getpid() ); //返回父进程的PID
printf( "\tparent ppid = %d\n", getppid() ); //返回父进程的父进程的PID
printf( "\tchild process exited with status %d \n", status );
}
exit(EXIT_SUCCESS);
子进程与父进程、getpid和getppid
最新推荐文章于 2025-01-11 20:50:18 发布