#include #include #include #include using namespace std; string getoutput(string command){ int fds[2]; // fds[0] is the read end, fds[1] is the write end pipe(fds); string return_value; pid_t pid = fork(); // fork will return twice! Once as the parent, once as the child if(pid){ // In this case, we are the parent process close(fds[1]); while(true){ char buffer[1024]; ssize_t readlen = read(fds[0], buffer, 1024); // and this, at the same time! if(readlen < 1) break; buffer[readlen] = 0; return_value += string(buffer); } wait(0); close(fds[0]); } else { // In this case, we are the child process dup2(fds[1], 1); system(command.c_str()); // this to happen exit(0); } return return_value; } int main(){ int pid = fork(); printf("hi %d\n", pid); if(pid) return 0; while(1){ // This loop is what the daemon will keep doing string usercount = getoutput("who | grep \"^[a-Z\\-]\"* -o | sort -u | wc -l"); string time = getoutput("date \"+%b%d %H:%M\""); time[time.length() - 1] = ' '; usercount[usercount.length() - 1] = ' '; getoutput("echo " + time + usercount + " >> user_count_log"); cout << time + usercount << endl; sleep(600); } return 0; }