training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

ex-9.2.c (900B)


      1 /*
      2  * Advanced Programming in the UNIX(r) Environment
      3  *
      4  * Exercise 9.2
      5 */
      6 
      7 #include <stdio.h>
      8 #include <stdlib.h>
      9 #include <unistd.h>
     10 #include <string.h>
     11 
     12 int
     13 main(int argc, char *argv[])
     14 {
     15    pid_t pid;
     16 
     17    strncpy(argv[0], "ex-9.2", strlen(argv[0]));
     18 
     19    if( (pid = fork()) )
     20       exit(1);
     21 
     22    if( (pid = fork()) == -1 ) {
     23       perror("fork");
     24       return EXIT_FAILURE;
     25    }
     26    else if( pid == 0 ) {	/* child */
     27       sleep(1); /* Wait for the parent to terminate (?) */
     28 
     29       if( setsid() == -1 ) { /* Start a new session */
     30          perror("setsid");
     31 	 return EXIT_FAILURE;
     32       }
     33 
     34       /* Some dirty output */
     35       printf("\n");
     36 
     37       system(
     38 #if defined(__linux__)
     39       "ps jx"
     40 #else
     41       "ps jx -otpgid"
     42 #endif
     43       );
     44 
     45       sleep(1);
     46    }
     47 
     48    /*
     49     * The parent just terminate
     50     * 
     51     *    ...
     52    */
     53 
     54    return EXIT_SUCCESS; /* Make C compiler happy! */
     55 } /* eof main() */
     56