anothertest
anothertest

Reputation: 979

Check that a ressource is shared by different proccess

I've written the following code in order to check if two proccess, let's call them pid1 and pid2 share the same process with their respective file descriptors.

1) I open a file in my first process. 2) Store the file descriptor. 3) Fork 4) Open the same file in the child process 5) Use kcmp to check

fd1 = open("test", O_RDWR | O_TRUNC | O_CREAT, 0600);
pid1 = getpid();
pid2 = fork();

if (!pid2) {
    pid2 = getpid();
    fd2 = open("test", O_RDWR | O_TRUNC);
    i = kcmp(pid1, pid2, 0, fd1, fd2);
    printf("%d\n", i);
}
else
{
    int status;
    int s;
    while ((s = wait(&status)) > 0);
}

To check this, I use the syscall kcmp with the flag KCMP_FILE (equivalent to 0). However the syscall always returns 1 or 2 instead of 0.

The expected result is 0 because the two proccess share the same resource with their file descriptors.

Did I misunderstand the man page or I am doing something wrong to check this?

Upvotes: 0

Views: 38

Answers (1)

John Bollinger
John Bollinger

Reputation: 181724

Did I misunderstand the man page or I am doing something wrong to check this?

You misunderstood the man page, which says this:

KCMP_FILE
          Check whether a file descriptor idx1 in the process pid1
          refers to the same open file description (see open(2)) as file
          descriptor idx2 in the process pid2.

The specific wording is deliberate and very important: for KCMP_FILE, kcmp() determines whether to FDs refer to the same open file description, which is a very different thing from refering to the same underlying file. Following the reference to open(2), we find:

A call to open() creates a new open file description, an entry in the system-wide table of open files.

(Emphasis added.) You have two calls to open(). Each creates its own new open file description. These are not the same, even though they refer to the same file, and kcmp() tells you so. The only way I know to get two distinct FDs in the same process that refer to the same open file description is via the dup() family of functions.

Upvotes: 1

Related Questions