Category: Utilities
Author/Contact Info zentara
Description:

This takes some c code which opens,closes or locks a cdrom; and uses swig to generate a perl interface. It is a simple example if you want to learn about swig, yet is useful.

Instructions:
Check your perl location for the -I for CORE location in step 3.
Run these commands in succession:

1. swig -perl5 cdrom.i
2. edit Cdrom.pm. Change @EXPORT=qw(cdeject cdclose cdlock)
3. gcc -fpic -c cdrom.c cdrom_wrap.c -Dbool=char -I/usr/lib/perl5/5.6.0/i586-linux/CORE
4. gcc -shared cdrom_wrap.o cdrom.o -o Cdrom.so
5. strip Cdrom.so
5. copy Cdrom.pm and Cdrom.so to someplace in @INC

then in the script
use Cdrom;

You may need to chmod 666 /dev/cdrom if you want user access.
/*cdrom.c*/
#include <sys/ioctl.h> 
#include <linux/cdrom.h> 
#include <fcntl.h> 

#define CDROM "/dev/cdrom"  
/* In all functions 'device' means name of CD-ROM device, 
* for example /dev/cdrom 
*/

/* Close CD-ROM tray */
int cdclose(char *device)
{
int fd = open(device, O_RDONLY|O_NONBLOCK);
if (fd == -1)
return -1;
if (ioctl(fd, CDROMCLOSETRAY) == -1)
return -1;
close(fd);
return 0;
}

/* Eject CD-ROM tray */
int cdeject(char *device)
{
int fd = open(device, O_RDONLY|O_NONBLOCK);
if (fd == -1)
return -1;
if (ioctl(fd, CDROMEJECT) == -1)
return -1;
close(fd);
return 0;
}

/* Lock (if lock==1) or unlock (if lock==0) CD-ROM tray */
int cdlock(char *device, int lock)
{
int fd;
fd = open(device, O_RDONLY|O_NONBLOCK);
if (fd == -1)
return -1;
if (ioctl(fd, CDROM_LOCKDOOR, lock) == -1)
return -1;
close(fd);
return 0;
}

/**********************************************************/
/**********************************************************/
/**********************************************************/

/* Cdrom.i */
%module Cdrom
%{
/* Put header files here (optional) */
%}
extern int cdclose(char *device);
extern int cdeject(char *device);
extern int cdlock(char *device, int lock);

/**********************************************************/
/**********************************************************/
/**********************************************************/
#cdrom.pl
###########################################
#!/usr/bin/perl

use Cdrom;

#cdclose($device); 
#cdeject($device); 
#cdlock($device,$lock); #lock=1 to lock  
                        #lock=0 to unlock 
#cdlock($device,1) 

$cdrom= '/dev/cdrom';
#$cdrom = '/dev/hdc';

cdeject($cdrom) or die $!;
sleep(5);
cdclose($cdrom) or die $!;
exit (0);
############################################
Replies are listed 'Best First'.
Re: cdrom tray control with swig
by Zaxo (Archbishop) on Sep 28, 2002 at 17:15 UTC

    What happens if the device is mounted?

    After Compline,
    Zaxo

Re: cdrom tray control with swig
by zentara (Cardinal) on Sep 28, 2002 at 18:02 UTC
    Thanks for ponting that out Zaxo. Added "or die $!" .