1819941 Members
3387 Online
109607 Solutions
New Discussion юеВ

Perl; open a file in vi

 
SOLVED
Go to solution
David_246
Trusted Contributor

Perl; open a file in vi

Hi,

I have an idea of opening a file and creating a lock-file for it.
Creating the lock-file and removing it is no problem. However opening the file is a bigger problem, It doesn't show my input (of course);

Any ideas how I should get the vi work ?

#!/usr/local/bin/perl
# Script that creates lock-file

$file=$ARGV[0];
@last_f=split(/\//, $file );
@last_f=reverse @last_f;
$last_f = $last_f[0];

if ( -f "/tmp/${last_f}" ) {
print "Sorry, $last_f is still opened by someone else \n";
}
else {
`touch /tmp/${last_f}`;
`/usr/bin/vi $file`;
`rm /tmp/$last_f`;
}

## I know I am missing quiet some perl-code here that is replace by `shell code`, you are allowed to improve it :) else I will find out myself on the internet.

Regs David
@yourservice
5 REPLIES 5
Steven E. Protter
Exalted Contributor

Re: Perl; open a file in vi

There is a perl function called flock()

It will lock the file while you have operations on it. Anyone else trying to do operations on the file will fail.

You can even allow reads while you are writing. Or not.

SEP
Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Perl; open a file in vi

You need the system() function.

e.g

my $cmd = sprintf("/usr/bin/vi %s",$file);
my $status = system($cmd);

I used sprintf to build up the command because you might need to form complex commands.


If it ain't broke, I can fix that.
David_246
Trusted Contributor

Re: Perl; open a file in vi

Hi Pete,

Great replacement for mine. My intention however is to make sure our admins always moderate an /etc/hosts file only by one in a time :)

So what I was looking for is a way of opening /etc/host like this :

openfile /etc/hosts

openfile would then be my perl-script instead of vi. Your solution solves the lock of the text file, but not the vi issue. Any ideas how in/ouput gets redirected back to my terminal ?

Regs David
@yourservice
David_246
Trusted Contributor

Re: Perl; open a file in vi

Hhhm, why are you leafheads always so good :)

Many thanks !!


Regs David
@yourservice
A. Clay Stephenson
Acclaimed Contributor

Re: Perl; open a file in vi

Lockf() or fcntl() would be of limited use in this context because UNIX file locks (unless you set some file mode bits) are advisory rather than mandatory. Unless the child process (vi, in this case -- and it don't) respects the lock then it will simply open the file completely ignoring the lock. You idea of a temporary lock file is actually a better approach BUT you need a signal handler to remove the lock file in case your script unexpectedly exits.
If it ain't broke, I can fix that.