(OK) ztgdaemon—守护进程

// gcc ztgdaemon.c -o ztgdaemon
/*
Server
nc -l 12123 < filename
iptables -I INPUT -p tcp --dport 12123 -j ACCEPT

Client
nc -n 1.2.3.4 12123 > filename
*/
// ssh -p 11111 1.2.3.4
// scp -r -P 11111 ztgdaemon 1.2.3.4:/root/ 
// ztgdaemon "nc -l 12123 < filename"

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>

void daemonize(void)
{
	pid_t  pid;

	/*
	 * Become a session leader to lose controlling TTY.
	 */
	if ((pid = fork()) < 0) {
		perror("fork");
		exit(1);
	} else if (pid != 0) /* parent */
		exit(0);
	setsid();

	/*
	 * Change the current working directory to the root.
	 */
//	if (chdir("/") < 0) {
//		perror("chdir");
//		exit(1);
//	} 

	/*
	 * Attach file descriptors 0, 1, and 2 to /dev/null.
	 */
	close(0);
	open("/dev/null", O_RDWR);
	dup2(0, 1);
	dup2(0, 2);
}

int main(int argc, char **argv)
{
    if (argc == 1)
    {
        printf("Usage: %s commond-string\n", argv[0]);
        exit(1);
    }


	daemonize();
	system(argv[1]);
	//while(1);
}

posted @   张同光  阅读(93)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示