linux下实现自动后台运行,脱离输出到终端
来源:互联网 发布:淘宝外卖会员卡好用吗 编辑:程序博客网 时间:2024/05/23 10:25
看sipp的源代码,看到里面有实现完全后台运行,即脱离了终端。不向终端打印任何信息。
代码如下:
#include <unistd.h>#include <stdio.h>#include <errno.h>#include <fcntl.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>#include <stdlib.h>#define BUFFER_SIZE 1024int main(int argc, char *argv[]){//return 0; pid_t l_pid; switch(l_pid = fork()) { case -1: // error when forking ! printf("Forking error"); exit(-1); case 0: // child process - poursuing the execution // close all of our file descriptors { int nullfd = open("/dev/null", O_RDWR); dup2(nullfd, fileno(stdin)); dup2(nullfd, fileno(stdout)); dup2(nullfd, fileno(stderr)); //sleep(100); close(nullfd); } break; default: // parent process - killing the parent - the child get the parent pid printf("Background mode - PID=[%d]\n", l_pid); exit(1); } printf("Background mode - PID=[%d]\n", l_pid); sleep(100);}
关闭了stdin stdout stderr,而父进程在exit(1)处结束,而子进程继续执行下面的sleep等代码。
这里
/dev/null是
把/dev/null看作"黑洞". 它非常等价于一个只写文件. 所有写入它的内容都会永远丢失. 而尝试从它那儿读取内容则什么也读不到. 然而, /dev/null对命令行和脚本都非常的有用.
The function fileno() examines the argument stream and returns its
integer descriptor.
dup2
dup2() makes newfd be the copy of oldfd, closing newfd first if neces‐
sary, but note the following:
If oldfd is not a valid file descriptor, then the call fails, and
newfd is not closed.
* If oldfd is a valid file descriptor, and newfd has the same value as
oldfd, then dup2() does nothing, and returns newfd.
解释下:fileno只是读取FILE *或流的int标志。
dup2 原型是:int dup2(int oldfd, int newfd); 将newfd是oldfd的一个拷贝,如果newfd打开,则先关闭它。
- linux下实现自动后台运行,脱离输出到终端
- Linux后台命令脱离终端
- 脱离终端后台运行 nohup xxx &
- Linux下使Shell 命令脱离终端在后台运行
- Linux下使Shell 命令脱离终端在后台运行
- Linux下使Shell 命令脱离终端在后台运行
- Linux下使Shell 命令脱离终端在后台运行
- Linux下使Shell 命令脱离终端在后台运行
- Linux下使Shell 命令脱离终端在后台运行
- Linux下使Shell 命令脱离终端在后台运行
- Linux下使Shell 命令脱离终端在后台运行
- Linux下使Shell 命令脱离终端在后台运行
- Linux下使Shell 命令脱离终端在后台运行
- 如何在后台运行 Linux 命令并且将进程脱离终端
- 如何在后台运行 Linux 命令并且将进程脱离终端
- 如何在后台运行 Linux 命令并且将进程脱离终端
- linux进程后端运行,脱离终端
- linux进程后端运行,脱离终端
- 启动- SCL Simulator for IEC61850
- CentOS TCP 性能优化
- [iOS] ios的runtime
- 开源软件keepalived实现分布式数据分发
- 在vs2010里自建cocos2dx工程,不依赖cocos2dx包
- linux下实现自动后台运行,脱离输出到终端
- 新项目1大幕开启
- VC/MFC之ListCtrl控件使用经验总结
- ZOJ 1880 Tug of War
- window下的Nginx+flup+django
- 2dx 动画
- java.lang.IllegalStateException: getOutputStream() has already been called for this response
- Android XML解析学习—Pull方式(HttpURLConnection xml)
- RTTI:获取类的详细信息