dup()
dup() システムコールは、ファイル記述子のコピーを作成します。
- 新しい記述子には、最も小さい番号の未使用の記述子が使用されます。
- コピーが正常に作成された場合は、オリジナルとコピーのファイル記述子を同じ意味で使用できます。
- これらは両方とも同じオープン ファイル記述を参照するため、ファイル オフセットとファイル ステータス フラグを共有します。
構文:
C#スイッチ
int dup(int oldfd);C
oldfd: old file descriptor whose copy is to be created.
// C program to illustrate dup() #include #include #include int main() { // open() returns a file descriptor file_desc to a // the file 'dup.txt' here' int file_desc = open('dup.txt' O_WRONLY | O_APPEND); if(file_desc < 0) printf('Error opening the filen'); // dup() will create the copy of file_desc as the copy_desc // then both can be used interchangeably. int copy_desc = dup(file_desc); // write() will write the given string into the file // referred by the file descriptors write(copy_desc'This will be output to the file named dup.txtn' 46); write(file_desc'This will also be output to the file named dup.txtn' 51); return 0; }
このプログラムにはファイルを開いて書き込みを行うことが含まれるため、オンライン コンパイラでは実行されないことに注意してください。
説明:
open() は、ファイル記述子 file_desc を「dup.txt」という名前のファイルに返します。 file_desc は、ファイル 'dup.txt' で何らかのファイル操作を行うために使用できます。 dup() システムコールを使用した後、file_desc のコピーが copy_desc 作成されます。このコピーは、同じファイル「dup.txt」に対して何らかのファイル操作を行うために使用することもできます。 2 つの書き込み操作の後、1 つは file_desc を使用し、もう 1 つは copy_desc を使用して同じファイル (「dup.txt」) が編集されます。コードを実行する前に、書き込み操作前のファイル「dup.txt」を次のようにします。
dbms の酸のプロパティ

上記の C プログラムを実行すると、ファイル「dup.txt」は次のようになります。

dup2()
dup2() システム コールは dup() に似ていますが、それらの基本的な違いは、最も小さい番号の未使用のファイル記述子を使用する代わりに、ユーザーが指定した記述子番号を使用することです。
構文:
int dup2(int oldfd int newfd);
oldfd: old file descriptor
newfd new file descriptor which is used by dup2() to create a copy.
重要な点:
BFSとDFS
- dup() および dup2() システム コールを使用するためのヘッダー ファイル unistd.h をインクルードします。
- 記述子 newfd が以前に開いていた場合は、再利用される前に暗黙的に閉じられます。
- oldfd が有効なファイル記述子でない場合、呼び出しは失敗し、newfd は閉じられません。
- oldfd が有効なファイル記述子で、newfd が oldfd と同じ値を持つ場合、 dup2() は何も行わず、newfd を返します。
dup2() システムコールのトリッキーな使い方:
dup2() と同様に、 newfd の代わりに任意のファイル記述子を置くことができます。以下は、標準出力 (stdout) のファイル記述子を使用する C 実装です。これにより、すべての printf() ステートメントが古いファイル記述子によって参照されるファイルに書き込まれるようになります。
C// C program to illustrate dup2() #include #include #include #include int main() { int file_desc = open('tricky.txt'O_WRONLY | O_APPEND); // here the newfd is the file descriptor of stdout (i.e. 1) dup2(file_desc 1) ; // All the printf statements will be written in the file // 'tricky.txt' printf('I will be printed in the file tricky.txtn'); return 0; }
これは、以下に示す図で確認できます。 dup2() 操作の前のファイル 'tricky.txt' を次のようにします。

上記の C プログラムを実行すると、ファイル「tricky.txt」は次のようになります。
クイズの作成