后台运行Linux程序,可以通过crontab设置,这种方法一般用来让一个程序定时运行,也可以通过./test &这样在程序末尾加上一个&使程序在后台运行。编写代码,下面我将参考httpd写一个程序使其运行不占控制台#include "detach.h"
void detach(void)
{
int x;
int pgrp; chdir("/"); if ((x = fork()) > 0)
exit(0); //exit parent, so we have the child
else if (x == -1) {
perror("fork");
fprintf(stderr, "unable to fork new process
");
exit(1);
} raise(SIGSTOP);
/* setsid - run a program in a new session*/
if ((pgrp = setsid()) == -1) {
perror("setsid");
fprintf(stderr, "setsid failed
");
exit(1);
} /* close out the standard file descriptors */
if (freopen("/dev/null", "r", stdin) == NULL) {
fprintf(stderr, "unable to replace stdin with /dev/null:
");
/* continue anyhow -- note we can"t close out descriptor 0 because we
* have nothing to replace it with, and if we didn"t have a descriptor
* 0 the next file would be created with that value ... leading to
* havoc.
*/
}
if (freopen("/dev/null", "w", stdout) == NULL) {
fprintf(stderr, "unable to replace stdout with /dev/null:
");
}
/* stderr is a tricky one, we really want it to be the error_log,
* but we haven"t opened that yet. So leave it alone for now and it"ll
* be reopened moments later.
*/
}Ubuntu下利用PPA源安装“侧翼面板”Linux内核常见数据结构及操作相关资讯 Linux教程
- Linux教程:如何在命令行中查看目 (07/28/2014 12:22:23)
- Linux 修改root密码 (11/03/2012 07:53:38)
- su - root 与su root的区别 (06/06/2012 00:39:40)
| - Linux进程间通信:消息队列 (01/28/2013 09:43:00)
- U盘安装Linux开机无法启动解决方法 (10/07/2012 08:55:52)
- Windows 7/Linux 同步时间 (05/15/2012 06:17:55)
|
本文评论 查看全部评论 (0)