Search code examples
clinuxfile-descriptor

How to know which input files are shared between two C programs?


When I execute two C Programs in Linux, I can print their local/private file descriptor by using fileno(). It means, when I run two independent programs side by side, and print fileno() in each of them, 3 is printed for the first file opened, 4 is printed for the second file opened and so on.

Therefore, by using fileno(), it is not possible to know which input files are shared between them.

Is there any way to print the input file name that is shared between two C programs?


Solution

  • use

    readlink /proc/<pid>/fd/* | sort -u > /tmp/process-<pid>.out
    

    to create a file with a list of all files opened by a process with PID <pid>. then use comm(1) to find the common files, as follows:

    comm -12 /tmp/process-<pid1>.out /tmp/process-<pid2>.out
    

    Note that this will list all files shared by these programs.

    if you know that the specific file descriptors used by the program are e.g. 3,4,5,9,11,12, then replace the first command with:

    readlink /proc/<pid>/fd/{3,4,5,9,11,12} | sort -u > /tmp/process-<pid>.out
    

    If you don't know the file descriptors, and you want to assume that all the file descriptors which are open for read (including stdin) are input files, you'll have to do something more clever by reading /proc/<pid>/fdinfo/<file-descriptor>, which prints a flags field, which has that information.