Question

I have a few programs. I run the main program/process A. It creates two pipes. When I print these descriptors, I have descriptors with numbers 3 and 4 for pipe one, and 5 and 6 for pipe two. Then program A creates two new processes B(B.cpp) and C(C.cpp) (with fork() and then execv()) and I put to them as argument second descriptor of pipe one(4) and for each new process I open different files(for B file b.txt and for C c.txt). When I print descriptors again, there is same descriptor for opened file b.txt and c.txt. I have used sleep(2) function so all processes are active. How is it possible? Shouldn't be descriptor for B and C different?

B:

#define FILENAME1 "b.txt"
static int des1;
static int des2;
....
des1 = open(FILENAME1, O_RDONLY);  
if(tempDes == -1){
  perror("Open");
  exit(EXIT_FAILURE);
}
printf("descriptors1: %d, %d\n", des1, des2);
....

C:

#define FILENAME2 "c.txt"
static int des1;
static int des2;
....
des1 = open(FILENAME2, O_RDONLY);  
if(tempDes == -1){
  perror("Open");
  exit(EXIT_FAILURE);
}
printf("descriptors2: %d, %d\n", des1, des2);
....

Console output: enter image description here

In b.txt:

sometexta
sometextb
...

In c.txt:

one
two
...
Was it helpful?

Solution

The kernel maintains a per-process table of file descriptors.

Otherwise a multi-user multi-process system could not even work, as the STDIN, STDOUT and STDERR file descriptors (0, 1, 2) of all processes would have to point to the same file (terminal), but they are obviously using independent terminals.

On the other hand, when you fork, the child process inherits all open file descriptors from the parent and they point to the same physical file. But files opened after the fork are independent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top