Question
In C, for Unix/Linux programming:
whotofile.c to modify:
Modify the whotofile.c sample program so it appends the output of who to a file. Make sure your program works if the file does not exist. Synopsis: ./whotofile A sample run: A sample run would result in a text fie containing the results of who.
Explanation / Answer
#include #include #include #include #include #include #define DFLMODE 0644 int main(int ac, char **av) { pid_t pid ; char *file = "userlist"; if ( ac > 1 ) file = av[1]; printf("About to run who into a file "); /* create a new process or quit */ if( (pid = fork() ) == -1 ){ perror("fork"); exit(1); } /* child does the work */ if ( pid == 0 ){ /* close then open */ close(1); if ( open(file,O_WRONLY|O_CREAT|O_APPEND,DFLMODE) != 1 ) perror(file); else { execlp( "who", "who", NULL ); /* and run */ perror("execlp"); } exit(1); } /* parent waits then reports */ if ( pid != 0 ){ wait(NULL); printf("Done running who. results in %s ", file); } return 0; }