アプリケーションが、リモートホストからマウントされたファイスシステム、または初期化が長期化する可能性のあるデバイス上の通常ファイルを動的に開く必要性が発生する場合があります。このようなファイルオープン作業を行っている場合、アプリケーションは他のイベントに対するリアルタイム応答が行えません。SunOS ではこの問題を解決するために、第 2 のプロセスに実際のファイルオープン作業を行わせ、ファイル記述子をリアルタイム処理に渡す機能が提供されています。
SunOS の STREAMS インタフェースでは 1 つのプロセスから別のプロセスへオープンファイル記述子を渡すメカニズムを装備しています。オープンファイル記述子を持つプロセス ioctl(2) 関数の引数 I_SENDFD を使用します。もう 1 つのプロセスは ioctl(2) の引数 I_RECVFD を使用してファイル記述子を取得します。
この例では、親プロセスはテストファイルに関する情報を出力し、パイプを作成します。次に親は、テストファイルを開き、パイプを使用してオープンファイル記述子を親へ戻す子プロセスを作成します。その後、親プロセスは新しいファイル記述子の状態情報を表示します。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stropts.h>
#include <stdio.h>
#define TESTFILE "/dev/null"
main(int argc, char *argv[])
{
int fd;
int pipefd[2];
struct stat statbuf;
stat(TESTFILE, &statbuf);
statout(TESTFILE, &statbuf);
pipe(pipefd);
if (fork() == 0) {
close(pipefd[0]);
sendfd(pipefd[1]);
} else {
close(pipefd[1])
recvfd(pipefd[0]);
}
}
sendfd(int p)
{
int tfd;
tfd = open(TESTFILE, O_RDWR);
ioctl(p, I_SENDFD, tfd);
}
recvfd(int p)
{
struct strrecvfd rfdbuf;
struct stat statbuf;
char fdbuf[32];
ioctl(p, I_RECVFD, &rfdbuf);
fstat(rfdbuf.fd, &statbuf);
sprintf(fdbuf, "recvfd=%d", rfdbuf.fd);
statout(fdbuf, &statbuf);
}
statout(char *f, struct stat *s)
{
printf("stat: from=%s mode=0%o, ino=%ld, dev=%lx, rdev=%lx¥n",
f, s->st_mode, s->st_ino, s->st_dev, s->st_rdev);
fflush(stdout);
}