Linux进程创建fork()

#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也能正确读取。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值