Gourish Singla
Gourish Singla

Reputation: 13

Check if a file is opened by other process without opening it in C (Linux environment)

Is there a way to check if file is opened, whether in read mode or write mode, by some other process in another terminal, without trying to open it?

My C code:

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>

int main() {
    FILE *demo;
    int result;

    if (getenv("FIRST_TIME")) {
        demo = fopen("distributed.txt", "r+");
        sleep(15);
        fclose(demo);
    } else {
        demo = fopen("distributed.txt", "r+");
        printf("demo is %p \n", demo);
    }
    return 0;
}

In first terminal FIRST_TIME env var is set, and opened the file there. In second terminal, there is no such env var set, so it should execute the else part. In the else part I want demo to have NULL till same file is opened by first terminal, and provide me with a value when file is closed in first terminal.

Better I don't want to try opening file till that file is closed by first terminal.

Upvotes: 1

Views: 160

Answers (1)

chqrlie
chqrlie

Reputation: 145287

There is no simple nor reliable way to achieve what you want because you cannot avoid race conditions without a proper lock on the file. Whether a method returns true or false for the test is the file xxx open by another process, the situation may change before your process acts on this information.

You can open the file for exclusive access with the open system call using the O_EXLOCK flag. In case of success, you can then use fdopen() to associate the file handle with a standard stream. Yet this does not seem to address your goal.

For your inter process communication problem, you should investigate named pipes.

Upvotes: 2

Related Questions