views:

139

answers:

6

Let's say I have: sample.c

int main (...) {

  char str*;

  get s through user input

  test(str);

  return 0;

}

void test (str) {

   copy str to new file 

   change file permissions on new file

   close file

}

There's no possibility of a race condition here since I have no threads in my main() method. Is that true?

+1  A: 

Another sources of race conditions are interrupts and signals. If you use neither then no race condition will occur (there is single racer)

Andrey
Although your answer is technically correct, every OS with pre-emptive scheduling uses interrupts to give each process its time slice. The absence of explicit interrupt code in this program does not mean that no interrupts will happen.
Thomas
A: 

That's correct. The race condition by definition requires multiple threads and at least one shared resource.

Brad
Multiple processes... one filesystem...
Thomas
Of course... I was trying to clarify for his program alone. It is probably good though that this is pointed out, so thank you for your comment.
Brad
+6  A: 

There is the possibility of a race - two users could run your program at the same time.

anon
@Neil- Whats the solution in this scenario?
Praveen S
@Praveen Depends on the filesystem. Some operations are normally atomic, and can be used for locking logic.
anon
Could you combine the first two steps of void test(str) to eliminate the race condition? Or could there still be a race condition since two users could call the same program?
Kevin
@Praveen: Eliminating that race is what the `O_EXCL` flag to `open(2)` is for.
caf
+7  A: 

There is a kind of race condition in that the user can exchange "new file" immediately before you change permissions of "new file". This is (was?) an often used security exploit.

I just see that Neil Butterworth had a related idea.

Peter G.
Thanks, Peter G and Neil Butterworth.
Kevin
A: 

Any time that you make a system call there is a possibility of a race condition. This is because the kernel links all the threads on the system and allows control interaction between processes. In this case another thread on the system can access the same file as your application.

doron
A: 

The boost::filesystem docs have good explanations of filesystem race conditions which are applicable to filesystems in general.

Dustin Getz