Posted By

gdonald on 09/27/06


Tagged

dev 69


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

copyleft


dev 69


 / Published in: C++
 

  1. # build: `gcc -o 69 69.c`
  2. # insert as root: `./69`
  3. # access: `cat /dev/69`
  4.  
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <sys/wait.h>
  8. #include <errno.h>
  9. #include <fcntl.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <unistd.h>
  14.  
  15. int daemon_init( void )
  16. {
  17. pid_t pid;
  18.  
  19. if ( ( pid = fork() ) < 0 )
  20. {
  21. return -1;
  22. }
  23. else if ( pid != 0 )
  24. {
  25. exit(0); /* parent exits */
  26. }
  27.  
  28. setsid();
  29. chdir( "/dev" );
  30. umask(0);
  31.  
  32. return 0;
  33. }
  34.  
  35. void create_fifo( char* filename )
  36. {
  37. if ( mknod( filename, S_IFIFO | 0600, 0 ) == -1 )
  38. {
  39. system( "mkfifo --mode=0600 /dev/69" );
  40. }
  41. }
  42.  
  43. void check_fifo( char* filename )
  44. {
  45. struct stat buf;
  46.  
  47. if ( stat( filename, &buf ) == -1 )
  48. {
  49. create_fifo(filename);
  50. if ( stat( filename, &buf ) == -1 )
  51. {
  52. exit(EXIT_FAILURE);
  53. }
  54. }
  55.  
  56. if ( !S_ISFIFO(buf.st_mode) )
  57. {
  58. if ( unlink(filename) == -1 )
  59. {
  60. exit(EXIT_FAILURE);
  61. }
  62. create_fifo(filename);
  63. }
  64. }
  65.  
  66. void monitor_fifo( char* filename )
  67. {
  68. while (1)
  69. {
  70.  
  71. int fd;
  72.  
  73. check_fifo(filename);
  74.  
  75. if ( ( fd = open( filename, O_WRONLY ) ) == -1 )
  76. {
  77. exit(EXIT_FAILURE);
  78. }
  79.  
  80. while (1)
  81. {
  82. write( fd, "69", strlen("69") );
  83. }
  84.  
  85. (void) close(fd);
  86.  
  87. sleep(1); /* to avoid dup sigs */
  88. }
  89. }
  90.  
  91. int main( int argc, char* argv[] )
  92. {
  93. if ( daemon_init() )
  94. {
  95. fprintf( stderr, "%s: Error initializing daemon\n", argv[0] );
  96. return -1;
  97. }
  98.  
  99. monitor_fifo("/dev/69");
  100.  
  101. return 0;
  102. }

Report this snippet  

You need to login to post a comment.