/ 开发首页 Symbian开发 移动开发 游戏策划 X-factory 源码 工具 资料 学问 论坛
如何在进程间共享文件句柄
www.playing.com.cn 2007-07-05 10:27

在许多情况下,在不同的两个进程之间共享文件会话和句柄是十分有必要的。解决放案有两种,他们是:继承关系或者客户端-服务器关系。

继承关系::

使用RFile::TransferToProcess和RFile::AdoptFromCreator函数,可以将文件在父进程和子进程之间进行共享。TransferToProcess()函数可以在父进程中进行调用,将一个打开的文件对象的所有权传递给他的子进程。

对连接的文件服务会话方面,必须调用RFs::ShareProtected()函数,将文件句柄标记为可共享的,这样文件句柄的传递才能够进行;否则的话RFile::TransferToProces函数的返回值将会是KErrBadHandle。同样,在子进程中,需要使用AdoptFromCreator()函数来对传递近来的文件句柄(RFile对象)进行接收。

代码示例:

CODE:
// In the parent process:
RFs fs;
User::LeaveIfError(fs.Connect());
CleanupClosePushL(fs);
User::LeaveIfError(fs.ShareProtected());

RFile file;
User::LeaveIfError(file.Replace(fs, KFile, EFileWrite | EFileShareAny));
CleanupClosePushL(file);

// Create test process
RProcess p;
User::LeaveIfError(p.Create(KChildProcess,  KNullDesC));
CleanupClosePushL(p);

// Transfer to process storing the RFs handle into environment  slot 1 and the
// RFile handle into slot 2

// NB slot 0 is reserved for the command line
User::LeaveIfError(file.TransferToProcess(p, 1, 2));

// Wait for handle to be transferred; wrap in an active object if blocking this
// thread is undesirable

TRequestStatus transStatus;
p.Rendezvous(transStatus);

if(transStatus != KRequestPending)
{ // Process creation failed
    p.RendezvousCancel(transStatus);
    p.Kill(0);
    User::Leave(transStatus.Int());
}

// Start the process
p.Resume();

User::WaitForRequest(transStatus);
User::LeaveIfError(transStatus.Int());

// Now we can safely close the fs
CleanupStack::PopAndDestroy(3); // close p, file, and fs
 
CODE:
// In the child process:
RFile file;

// Adopt the file using the RFs handle into environment  slot 1 and the RFile
// handle into slot 2
User::LeaveIfError(file.AdoptFromCreator(1,2));
CleanupClosePushL(file);

RProcess::Rendezvous(KErrNone); // Signal transfer completed successfully

// . . . Do the neccessary file operations

CleanupStack::PopAndDestroy(); // close file

客户端服务器关系:

和继承关系类似,客户端服务器关系的进程也可以进行文件句柄共享,使用的函数是RFile::TransferXXX和RFile::AdoptXXXAPI,同样客户端服务器共享模式也需要使用RFs::ShareProtected()函数将文件句柄标记为可共享的,这样文件句柄的传递才能够进行;否则的话RFile::TransferToProces函数的返回值将会是KErrBadHandle。同样,在客户端进程中,需要使用AdoptFromCreator()函数来对传递近来的文件句柄(RFile对象)进行接收。

服务器进程使用RFile::TransferToClient()函数向客户端传递文件句柄,客户端进程使用RFile::AdoptFromServer()函数进行文件句柄接收。要想送客户端向服务器传递文件句柄,需要使用的函数是RFile::TransferToServer()和RFile::AdoptFromClient()。
(转自:开发工厂)