#include <iostream>
#include <sys/types.h>
#include <unistd.h>
int main() {
string message;
int n;
auto pid=fork();
if (pid<0) //如果为负数则创建失败!
{
std::cout << "process is err" << std::endl;
}
if (pid==0)//如果创建成功,则会返回0值,以下操作为子进程操作范畴
{
message="This is the child";
n=6;
}
else //此为父进程操作范畴!
{
message="This is the parent!";
n=3;
}
for (; n>0; n--)//定义了父子进程循环输出为3/6次,间隔一秒
{
std::cout << message << std::endl;
sleep(1);
}
return 0;
}
输出结果
root@kali:~/Desktop/Demo# g++ 1.cpp
root@kali:~/Desktop/Demo# ./a.out
This is the parent!
This is the child
This is the parent!
This is the child
This is the parent!
This is the child
This is the child
root@kali:~/Desktop/Demo# This is the child
This is the child
最基本的创建进程的方法。
首先使用fork函数,其返回值类型为pid_t,即一个自定义整数类型。
如果创建成功则会返回0值,利用其返回值进行操作,所以程序中会出现判断语句。
当pid为0时,则为子进程的操作范畴,当pid大于不等于0时,则为父进程的操作范畴!
利用fork()函数的返回值,区分父子线程进行操作!
程序是在Shell下运行的,因此Shell进程是父进程的父进程。父进程运行时Shell进程处于等待状态,当父进程终止时Shell进程认为命令执行结束了,于是打印Shell提示符,而事实上子进程这时还没结束,所以子进程的消息打印到了Shell提示符后面。最后光标停在This is the child的下一行,这时用户仍然可以敲命令,即使命令不是紧跟在提示符后面,Shell也能正确读取。