您的位置:首页 > 运维架构 > Linux

在Unix/Linux中创建一个后台进程的步骤

2012-12-14 20:04 411 查看
http://www.linuxidc.com/Linux/2011-07/39587.htm

在Unix/Linux中创建一个后台进程的步骤

1、调用fork函数,创建一个子进程。

2、先让父进程自然结束。

3、在子进程中调用setpgrp(),把子进程的进程组ID设为子进程的进程ID。

4、在子进程中调用setsid(),创建一个新的Session(会话),这样子进程就与当前的控制终端脱离,也接受不到当前终端的(ctrl + c)消息。

实现代码如下(运行环境:虚拟机下的Ubuntu):

/*
* Author: ACb0y
* FileName: main.cpp
* Create Time: 2011-07-24
* Version: V1.0
*/
#include <iostream>

#include <unistd.h>

using namespace std;

void print()
{
int pid = getpid();
int gid = getpgid(0);
cout << "process group id = " << gid << endl;
cout << "process id = " << pid << endl;
}

int main()
{
//create a child process.

int pid = fork();
if (-1 == pid)
{
cout << "call function fork() error!" << endl;
}
else if (0 == pid) //return from child process.

{
cout << "----------in child process.----------" << endl;
print();
cout << "--------------------------------------" << endl;
//将该进程的进程组ID设置为该进程的进程ID。

setpgrp();
cout << "----------in child process. setpgrp()----------" << endl;
print();
cout << "--------------------------------------" << endl;
//创建一个新的Session,断开与控制终端的关联。也就是说Ctrl+c的触发的SIGINT信号,该进程接收不到。

setsid();


for (int i = 0; i < 5; ++i)
{
sleep(20);
cout << "----------in child process.----------" << endl;
print();
cout << "--------------------------------------" << endl;
}
}
else //return from parent process.

{
cout << "----------in parent process.----------" << endl;
print();
cout << "--------------------------------------" << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: