Be a Supporter!

Code Snippet - eject cd rom

  • 186 Views
  • 0 Replies
New Topic Respond to this Topic
polym
polym
  • Member since: Oct. 2, 2007
  • Offline.
Forum Stats
Member
Level 14
Audiophile
Code Snippet - eject cd rom 2013-03-08 03:36:02 Reply

So my friend has a series of servers across the country, and I have ssh access with gcc 4.7.2. I thought it would be hilarious to write a program to eject the server's cd drive and write 'jihad' to the screen (especially since it's located in the laundry room.) To be specific, he has a hub server called 'redirect', and I ssh into the specific server that has gcc 4.7.2 (the servers have different package configurations.) It's centos/fedora.

#include <sys/types.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <linux/cdrom.h>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <getopt.h>

using namespace std;

void print_usage() {
	printf("-h, --help              Displays this text.\n");
	printf("-o, --open, -e, --eject Opens the tray.\n");
	printf("-c, --close             Closes the tray.\n");
}

int main(int argc,char **argv)
{
	string prefix = "/dev/";
	string devices[] = { "sr0", "cdrw1", "dvd1", "dvdrw1", "cdrom1" };
	int cdrom;                           /* CDROM device file descriptor */

	int next_option;

	const char* const short_options = "hoec";

	const struct option long_options[] = {
	{ "help", 0, NULL, 'h' },
	{ "open", 0, NULL, 'o' },
	{ "eject", 0, NULL, 'e' },
	{ "close", 0, NULL, 'c' },

	{ NULL, 0, NULL, 0 }
	};

	long cdrom_option = CDROMCLOSETRAY;

	next_option = getopt_long (argc, argv, short_options,
		long_options, NULL);
	if (next_option == -1) {
		print_usage();
		return 0;
	}
				
	do {
		switch (next_option)
		{
			case 'h':
				print_usage();
				return 0;
				break;
			case 'c':
				cdrom_option = CDROMCLOSETRAY;
				break;
			case 'o':
			case 'e':
				cdrom_option = CDROMEJECT;
				break;
			case -1:
				break;
			default:
				return 1;
		}
			
		next_option = getopt_long (argc, argv, short_options,
			long_options, NULL);
	}
	while (next_option != -1);

	for (int i = 0; i < 5; i++) {
	   if ((cdrom = open((prefix+devices[i]).c_str(),O_RDONLY | O_NONBLOCK)) < 0) {
			perror("open");
			exit(1);
	   }

	   if (ioctl(cdrom,cdrom_option,0)<0) {
			perror("ioctl");
			exit(1);
	   }

	   if (ioctl(cdrom,CDROM_DRIVE_STATUS) == CDS_TRAY_OPEN) {
			printf("%s%s", (prefix+devices[i]).c_str(), " is open.\n");
	   } else {
			printf("%s%s", (prefix+devices[i]).c_str(), " is closed.\n");
	   }
	   
	   printf("jihad\n");

	   close(cdrom);
	}
	return 0;
}
tom is awesome : ~ $ ./ot -o
/dev/sr0 is open.
jihad
/dev/cdrw1 is open.
jihad
/dev/dvd1 is open.
jihad
/dev/dvdrw1 is open.
jihad
/dev/cdrom1 is open.
jihad

Not really a practical or impressive example, just wanted to share it with you guys.