Saturday, May 22, 2010

I am working on a C++ program for UNIX that will use files as semaphores, please help.?

OK, so I'm supposed to use the creat() function in C++ with UNIX to create 5 files and only 5 files. I then want to test to see if those files are in use by using creat() on them again. My professor states that when creat() makes a new file, it is open for writing, however, when it truncates an existing file, it fails if there is no write permission. This allows a file to be used as a semaphore.





Here is my code:





#include %26lt;sys/types.h%26gt;


#include %26lt;sys/stat.h%26gt;


#include %26lt;fcntl.h%26gt;


#include %26lt;iostream%26gt;


#include %26lt;unistd.h%26gt;





using namespace std;





int main() {


int fd, fd2;


mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;


char *filename = "Fork1.txt";


char *filename2 = "Fork1.txt";





fd = creat("Fork1.txt", mode);


fd2 = creat("Fork1.txt", mode);





cout %26lt;%26lt; "Test" %26lt;%26lt; endl %26lt;%26lt; fd %26lt;%26lt; endl %26lt;%26lt; fd2 %26lt;%26lt; endl;


return 0;


}





The second creat() should return -1 as an error because the file already exists, but it is returning a successful value...please help! Thx.

I am working on a C++ program for UNIX that will use files as semaphores, please help.?
read the man page for open(2). There's an O_EXCL mode flag that implies exclusive. That flag, in create, would cause create to fail if the file exists. Is that what you are needing?
Reply:Larry is right!





O_EXCL


If O_CREAT and O_EXCL are set, open() shall fail if the file exists. The check for the existence of the file and the creation of the file if it does not exist shall be atomic with respect to other threads executing open() naming the same filename in the same directory with O_EXCL and O_CREAT set. If O_EXCL and O_CREAT are set, and path names a symbolic link, open() shall fail and set errno to [EEXIST], regardless of the contents of the symbolic link. If O_EXCL is set and O_CREAT is not set, the result is undefined.


No comments:

Post a Comment