naufalphew

daemon

Apr 15th, 2021
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.18 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <fcntl.h>
  6. #include <errno.h>
  7. #include <unistd.h>
  8. #include <syslog.h>
  9. #include <string.h>
  10.  
  11. int main() {
  12.   pid_t pid, sid;        // Variabel untuk menyimpan PID
  13.  
  14.   pid = fork();     // Menyimpan PID dari Child Process
  15.  
  16.   /* Keluar saat fork gagal
  17.   * (nilai variabel pid < 0) */
  18.   if (pid < 0) {
  19.     exit(EXIT_FAILURE);
  20.   }
  21.  
  22.   /* Keluar saat fork berhasil
  23.   * (nilai variabel pid adalah PID dari child process) */
  24.   if (pid > 0) {
  25.     exit(EXIT_SUCCESS);
  26.   }
  27.  
  28.   umask(0);
  29.  
  30.   sid = setsid();
  31.   if (sid < 0) {
  32.     exit(EXIT_FAILURE);
  33.   }
  34.  
  35.   if ((chdir("/")) < 0) {
  36.     exit(EXIT_FAILURE);
  37.   }
  38.  
  39.   close(STDIN_FILENO);
  40.   close(STDOUT_FILENO);
  41.   close(STDERR_FILENO);
  42.  
  43.   while (1) {
  44.     // Tulis program kalian di sini
  45.     pid_t child_id;
  46.     int status;
  47.     if (child_id == 0) {
  48.     // this is child
  49.  
  50.     char *argv[] = {"mkdir", "-p", "folderku", NULL};
  51.     execv("/bin/mkdir", argv);
  52.   } else {
  53.     // this is parent
  54.     while ((wait(&status)) > 0);
  55.     char *argv[] = {"touch", "folderku/fileku.txt", NULL};
  56.     execv("/usr/bin/touch", argv);
  57.   }
  58.     sleep(30);
  59.   }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment