linux daemonize child process

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>

int main(int argc, char* argv[]){
	int status;
	pid_t pid = fork();
	
	if(-1 == pid){
		perror("Fork Error");
	}else if (0 == pid ){
		strcpy(argv[0], "pid child process");
		setsid();
		while(1){
			printf("Hello world\n");
			sleep(5);
		}		
	}else{
		strcpy(argv[0], "pid parent process");
		printf("the child pid is %d\n", wait(&status));
		exit(0);
	}
}


gcc -o pid pid.c
./pid
exit
ps aux | grep pid
kill -9

猜你喜欢

转载自j4s0nh4ck.iteye.com/blog/2237931