精华区 [关闭][返回]

当前位置:网易精华区>>讨论区精华>>编程开发>>C/C++>>技术精解:内存、进程、线程等>>将一个进程推入后台的代码

主题:将一个进程推入后台的代码
发信人: jalinsoo()
整理人: wenbobo(2002-12-27 15:55:46), 站内信件
【 在 tjam (江南才子) 的大作中提到: 】
: 【 在 girlrong (阿蓉) 的大作中提到: 】
: :     因我对unix下的c编程一窍不通,板斧ken_qian极少来c版。又有网友反应c版
: : 讨论unix下的c编程的文章太少,故征求板斧若干。要求熟悉unix下的c编程,且
: : 愿意解答网友的相关问题,有空撰写有关unix下的c编程的文章。欢迎各位高手踊
:    .......
可惜我的时间不是很多,不然倒可以略尽绵力 
下面送给大家一段将一个进程推入后台的代码吧 

#include <signal.h>
#include <errno.h>
#include <sys/resource.h>


/*--------------------------------------------------------------------
----------
 * Detach a daemon process from login session controlling terminal
 *--------------------------------------------------------------------
----------
 */

int daemon_start()
{
register int childpid, fd;
struct rlimit rl;

/*
 * If we were not started in the background, fork and
 * let the parent exit. This also guarantees the first child
 * is not a process group header.
 */

if ((childpid = fork()) < 0)
return(-1);
else if (childpid > 0)
exit(0);   /* parent */

/*
 * First child process.
 * Disassociate from controlling terminal and process group.
 * Ensure the process can't reacquire a new controlling terminal.
 */

if (setpgrp() < 0) return(-1);

signal(SIGHUP,SIG_IGN); /* immune from pgrp leader death */

if ((childpid = fork()) < 0)
return(-1);
else if (childpid > 0)
exit(0);   /* first child */

/*
 * Second child
 * Close any open file descriptors.
 */
getrlimit(RLIMIT_NOFILE, &rl);
for (fd=rl.rlim_cur; fd>=0 ; --fd)
close(fd);
errno = 0;   /* probably got set to EBADF from a close */

/*
 * Move the current directory to root, to make sure we
 * aren't on a mounted filesystem.
 */
chdir("/");

/*
 * Clear any inherited file mode creation mask.
 */
umask(0);

signal(SIGCLD,SIG_IGN);

#ifdef SIGTTOU
         signal(SIGTTOU,SIG_IGN);
         signal(SIGTTIN,SIG_IGN);
         signal(SIGTSTP,SIG_IGN);
#endif
        signal(SIGINT,SIG_IGN);
        signal(SIGTERM,SIG_IGN);


return(0);
}



--
※ 来源:.月光软件站 http://www.moon-soft.com.[FROM: 202.96.183.48]

[关闭][返回]