(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
", argv[0]);
        exit(1);
    }


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

原文地址:https://www.cnblogs.com/ztguang/p/12646890.html