/********************************************************************* * C program fork process causes PHP execution not to quit * Description: * Since the test Gpio program needs to run continuously, while the main process needs to process other transactions but exits * because the child thread does not end up causing the PHP system call function not to quit, the solution is double fork (the first * Fork produces a child process for kill to let the second fork out of the child process into the orphan process) and converts the final * sub-process into a daemon, which does not affect PHP's acquisition of master process data. * * 2017-8-16 Shenzhen Longhua gen Zengjianfeng ************************************************************* *******/First, reference documents:1. Implementation of the Linux daemon http://alfred-sun.github.io/blog/2015/06/18/daemon-implementation/Second, test daemon Demo: #include<stdio.h>#include<stdlib.h>#include<string.h>#include<time.h>#include<unistd.h>#include<sys/param.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>//Daemon Initialization function voidInit_daemon () {pid_t pid; inti =0; if(PID = fork ()) = =-1) {printf ("Fork Error!\n"); Exit (1); } if(PID! =0) {exit (0);//Parent Process Exits} setsid (); //the child process opens a new session and becomes the conversation first process and leader process if(PID = fork ()) = =-1) {printf ("Fork Error!\n"); Exit (-1); } if(PID! =0) {exit (0);//End first child process, second child process is no longer the session first process} chdir ("/ tmp");//change the working directoryUmask0);//Resetting the file mask for(; i < getdtablesize (); + +i) {close (i); //Close Open File descriptor } return; } intMainintargcChar*argv[]) { intFP; time_t T; CharBuf[] = {"This is a daemon:"}; Char*datetime; intLen =0; //printf ("The Nofile is:%d\n", nofile); //printf ("The Tablesize is:%d\n", getdtablesize ()); //printf ("The PID is:%d\n", Getpid ()); //initializing the Daemon processInit_daemon (); //record running status every minute while(1) { if(-1= = (fp = open ("/tmp/daemon.log", o_creat| o_wronly| O_append,0600)) {printf ("Open File Error!\n"); Exit (1); } Len=strlen (BUF); Write (FP, buf, Len); T= Time (0); DateTime= Asctime (LocalTime (&t)); Len=strlen (datetime); Write (FP, datetime, Len); Close (FP); Sleep ( -); } return 0; }
C Program fork process causes PHP execution not to quit