Some system calls close by an if statement but others open after a variable is declared

StackOverflow https://stackoverflow.com/questions/22262883

  •  11-06-2023
  •  | 
  •  

質問

What's the difference with my question?

 fd = shm_open(argv[1], O_RDWR_O);
 if (fd == -1)
      errExit("shm_open");
 ....
 ....
 if(close(fd) == -1)
      errExit("close");     /* 'fd' is no longer needed */

I don't understand how the close statement closes the file descriptor with just an if statement?

Why don't they close it before-hand and then do the if statment?

Do you understand my question? Else I can try to think of how to rephrase it or elaborate..

役に立ちましたか?

解決

You could write the second statement as;

int tmp; 

...

tmp = close(fd);
if(tmp == -1)
   errExit("close");

But since tmp serves no purpose after the check in the if (and a good compiler will indeed optimise it away), it has the same effect if you write it as the original code.

On the other hand, we can use assignments in if-statements, so:

 if ((fd = shm_open(argv[1], O_RDWR_O)) == -1)
      errExit("shm_open");

will also work.

The key here is that the first one does indeed store a value that we want to use later (if successfully opening the shared memory), so it's clearer to write it as two separate statements, rather than "hiding" it in the if-statement.

On the other hand, in the second case, we have no use for the result of close, so there's no purpose to writing an extra line and have an extra variable.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top