[[oktatas:linux|< Linux]] ====== Démon programozás ====== * **Szerző:** Sallai András * Copyright (c) Sallai András, 2018 * Licenc: GNU Free Documentation License 1.3 * Web: http://szit.hu ===== A démonkészítés lépései ===== * gyermek folyamat létrehozása (fork) * a fájlmód mask-ról umask-ra állítása, * hogy a démon írhasson az általa létrehozott fájlokba * naplófájl megnyitása írásra * munkamenet azonosító létrehozása * Session ID (SID) * a gyermekfolyamatnak szükség van a kerneltől egy ilyen démon azonosítóra * másként árva lesz a gyermekfolyamat * az aktuális munkakönyvtár biztonságos helyre váltása * olyan könyvtárra kell állítani ami biztosan mindig létezik a Linuxos rendszerben * a gyökér mindig létezik * bezárjuk a szabványos fájlleírókat * biztonsági kockázat ha nyitvamard * a démon úgy sem tudja használni * a démon tevékenységének kódja ===== Linux démon forrása ===== Az alábbi mintaprogram Devin Watson munkája. BSD licenc alatt terjeszthető. #include #include #include #include #include #include #include #include #include int main(void) { /* Our process ID and Session ID */ pid_t pid, sid; /* Fork off the parent process */ pid = fork(); if (pid < 0) { exit(EXIT_FAILURE); } /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { exit(EXIT_SUCCESS); } /* Change the file mode mask */ umask(0); /* Open any logs here */ /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { /* Log the failure */ exit(EXIT_FAILURE); } /* Change the current working directory */ if ((chdir("/")) < 0) { /* Log the failure */ exit(EXIT_FAILURE); } /* Close out the standard file descriptors */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); /* Daemon-specific initialization goes here */ /* The Big Loop */ while (1) { /* Do some task here ... */ sleep(30); /* wait 30 seconds */ } exit(EXIT_SUCCESS); } Fordítás: gcc -o demon demon.c Futtatás: ./demon Leállítás: kiallall demon ===== Egyszerű fájlba író démon ===== #include #include #include #include #include #include int main(int argc, char* argv[]) { FILE *fp= NULL; pid_t pid = 0; pid_t sid = 0; int i = 0; pid = fork();// új folyamat elágaztatása if (pid < 0) { printf("elágaztatás sikertelen!\n"); exit(1); } if (pid > 0) { // a szülőfolyamat printf("A gyermekfolyamat azonosítója: %d \n", pid); exit(0); //A szülőfolyamat sikeres befejezése } umask(0);//fájlmód beállítása sid = setsid();//új munkamenet beállítása if(sid < 0) { exit(1); } close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); fp = fopen ("naplo.txt", "w+"); while (1) { sleep(1); fprintf(fp, "%d", i); fflush(fp); } fclose(fp); return (0); } Fordítás: gcc -o demon demon.c Futtatás: ./demon ===== Forrás ===== * http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html (2018) * http://www.microhowto.info/howto/cause_a_process_to_become_a_daemon_in_c.html (2018) * https://www.brettlischalk.com/posts/linux-daemon (2018)