Amit Shadadi
Amit Shadadi

Reputation: 637

Change child process's parent

i was searching how to do it for about 6 hours,but didn't find a way.

Is there any way i can change a process's parent process? some api maby ?

google didn't gave much, same for this site, so i opened new question.

What i'm trying to do is to lock a file for personal use, then delete it. i create the file on program A and use it with program B, when B finish the use, i delete with A, the thing is that B creates a sub process, which don't have B as his parent, so when i use :

File.Open(_moviePath, FileMode.Open, FileAccess.Read, FileShare.Inheritable);

I try to lock the file because i don't want other programs/users to be able to copy it but it failes.

tnx.

Upvotes: 0

Views: 463

Answers (1)

T McKeown
T McKeown

Reputation: 12857

instead of locking the file this way, why not use Mutex? It allows for cross process locking. This will work fine if this is to remain on a single box. http://msdn.microsoft.com/en-us/library/bwe34f1k(v=vs.110).aspx

And no you cannot reassign a parent process owner to a child process.

Here is an example, i will explain below: http://www.dotnetperls.com/mutex

using System; using System.Threading;

class Program
{
   static Mutex _m;

   static bool IsMutexExisting(string token)
   {  
    try  
    {
      // Try to open existing mutex.
      Mutex.OpenExisting(token);
    } 
    catch
    {
      return true;
     }
     // More than one instance.
   return false;
   }

So in your example program A will do it's thing and then wait.. how to get A to wait?

Have program A attempt to open an existing mutex (a mutex that only B will create), for example... pcode:

 while( IsMutexExisting("B Token") == false )
 {
     System.Threading.Thread.Sleep(500);  //sleep for a 1/2 sec
 }
 //ok, B has created the mutex, let's wait for it to be released indicating it is complete.
Mutex m = Mutex.OpenExisting("B Token");
m.WaitOne();  // will block execution until B releases the Mutex

 // lock created, this means B signaled us

 // do the rest of A code here...

Program B:

 <does what it does>
 //Create Mutex to signal A
 Mutex m = null;
 try{
     m =new Mutex(true,"B Token");

 ...
 ...
 }
 finally{
    m.ReleaseMutex();
 }

Upvotes: 1

Related Questions