Unix/Linux如何創建一個後臺進程(run background process)

Unix/Linux如何創建一個後臺進程
在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;
}


發佈了270 篇原創文章 · 獲贊 12 · 訪問量 52萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章