void SetPidFile(char* Filename) { FILE* f; f = fopen(Filename, "w+"); if (f) { fprintf(f, "%u", getpid()); fclose(f); } } int main( int argc, char** argv ) { char toolfile[32]; char folder[32]; intptr_t ret; FILE* logfile; if( argc!=3 ) { printf( "Write address of the program and name: /home/ubuntu/tool/ tool\n"); return -1; } pid_t pid, sid; pid = fork(); if (pid < 0) { sleep(1); return -1; } //We got a good pid, Close the Parent Process if (pid > 0) { return 0; } //Create a new Signature Id for our child sid = setsid(); if (sid < 0) { return -1; } //Change File Mask umask(0); //Save PID memcpy( toolfile, argv[0], strlen(argv[0]) ); memcpy( toolfile + strlen(argv[0]), ".log", 4 ); memset( toolfile + strlen(argv[0]) + 4, 0, 1 ); printf( "Daemon:: log to:%s\n", toolfile ); logfile = fopen( toolfile, "w" ); fprintf( logfile, "Daemon:: started with 0=%s 1=%s 2=%s\n", argv[0], argv[1], argv[2] ); memset( toolfile, 0, 32 ); memcpy( toolfile, argv[0], strlen(argv[0]) ); memcpy( toolfile + strlen(argv[0]), ".pid", 4 ); memset( toolfile + strlen(argv[0]) + 4, 0, 1 ); SetPidFile( toolfile ); fprintf( logfile, "Daemon:: PID=%u saved in the %s\n", getpid(), toolfile ); memset( folder, 0, 32 ); memcpy( folder, argv[1], strlen(argv[1]) ); fflush ( logfile ); memset( toolfile, 0, 32 ); memcpy( toolfile, folder, strlen(argv[1]) ); memset( toolfile + strlen(argv[1]), '/', 1 ); memcpy( toolfile + strlen(argv[1]) + 1, argv[2], strlen(argv[2]) ); //Change Directory //If we cant find the directory we exit with failure. if ((chdir(folder)) < 0) { fprintf( logfile, "Daemon:: Program folder was not found:%s\n", folder ); fclose( logfile ); return -1; } //Close Standard File Descriptors close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); fprintf( logfile, "Daemon:: Program started\n" ); fflush ( logfile ); ret = execl( toolfile, folder, NULL ); if( ret==-1 ) { fprintf( logfile, "Daemon:: execl error: %s. File=%s Folder=%s\n", strerror(errno), toolfile, folder ); fclose( logfile ); return -1; } fprintf( logfile, "Daemon:: closed\n" ); fclose( logfile ); return 0; }