#include #include // open at least #include // open #include // open #include // read using namespace std; // Create a race condition as the book describes. // The parent: // fork, // try to open a file read only and fail. // it will then usleep to simulate a time slice expiring // It will then open the file O_CREAT // And will then clobber the child data. // The child // sleep // try to open a file read only and fail. // It will then open the file O_CREAT // Write data const char * file="ConfigFile"; int main() { pid_t id; int fd; int openFlags; mode_t filePerms; string message; // remove the file if it exsts unlink(file); filePerms = S_IRUSR | S_IWUSR; id = fork(); // child take a nap; if (!id) { message = "I AM A CHILD"; usleep(10000); } else { message = "I AM A PARENT"; } cout << message << endl; fd = open(file, O_WRONLY); if (!fd) { cout << message << " and I am not a controlling process " << endl; } if (fd == -1) { // parent sleep now. if (id) { usleep(100000); } fd = open(file,O_WRONLY|O_CREAT, filePerms); write(fd,message.c_str(), message.size()*sizeof(char)); cout << message << " and I think I am the controling process" << endl; } close(fd); return 0; }