How to eject the CD Drive on Linux using C? - c

I was reading through this Advanced Linux Programming tutorial when I encountered a problem. I was trying to eject the CD-ROM drive using this code:
int fd = open(path_to_cdrom, O_RDONLY);
// Eject the CD-ROM drive
ioctl(fd, CDROMEJECT);
close(fd);
Then I try to compile this code and get the following output:
In file included from /usr/include/linux/cdrom.h:14,
from new.c:2:
/usr/include/asm/byteorder.h: In function ‘___arch__swab32’:
/usr/include/asm/byteorder.h:19: error: expected ‘)’ before ‘:’ token
/usr/include/asm/byteorder.h: In function ‘___arch__swab64’:
/usr/include/asm/byteorder.h:43: error: expected ‘)’ before ‘:’ token
So what am I doing wrong?

The error message you're seeing looks like something is wrong in your #include lines, not with the code you posted. I tried compiling http://www.advancedlinuxprogramming.com/listings/chapter-6/cdrom-eject.c and it compiles just fine.

According to this, you need to specify O_NONBLOCK when opening the device, otherwise it won't work.
From that page:
cdrom = open(CDDEVICE,O_RDONLY | O_NONBLOCK)

You are missing a #include, I think. Do you have:
#include <fcntl.h>
#include <linux/cdrom.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
Those are the ones in the example...

In the previous examples the following includes are not needed.
#include <sys/stat.h>
#include <sys/types.h>
Also as stated before you may need to open with O_NONBLOCK
You can find more options for interacting with the CDROM device in the header file located at '/usr/include/linux/cdrom.h' or here https://github.com/torvalds/linux/blob/master/include/uapi/linux/cdrom.h
Also here is another example for opening and closing the CD tray with the mentioned changes.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <linux/cdrom.h>
#include <sys/ioctl.h>
#include <unistd.h>
int main (int argc, char* argv[])
{
// Path to CD-ROM drive
char *dev = "/dev/dvd";
int fd = open(dev, O_RDONLY | O_NONBLOCK);
if(fd == -1){
printf("Failed to open '%s'\n", dev);
exit(1);
}
printf("fd :%d\n", fd);
// Eject the CD-ROM tray
ioctl (fd, CDROMEJECT);
sleep(2);
// Close the CD-ROM tray
ioctl (fd, CDROMCLOSETRAY);
close(fd);
return 0;
}

The open syscall has some unwanted behaviours which must be handled by setting it to Not blocking ie O_NONBLOCK
Also check that you have included the header file
#include <linux/cdrom.h>

Related

Setting Permissions to a file in C to Read Only

I'm new to C programming and I'm trying to experiment with setting the permissions of a file to Read Only. I'm sure that I don't have the directives correct and when I try to compile I get the error on the line that #include <io.h> is on "fatal error: io.h no such file or directory". The file 'time.log' is in a directory called 'time_logs' and the program will run from the same directory that the directory 'time_logs' is in.
OS is Rasbian for Raspberry Pi 4 Arm Using GCC
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <io.h>
#include <sys.h>
struct stat st = {0};
int main(void){
if(_chmod("time_logs/time.log", _S_IREAD) == -1)
perror("Not found");
else{
_chmod("time_logs/time.log", _S_IREAD);
}
}
It looks like you used a Windows manual trying to code for Linux.
#include <unistd.h>
#include <sys/stat.h>
if(chmod("time_logs/time.log", S_IRUSR | S_IRGRP | S_IROTH) == -1)
perror("time_logs/time.log");
But most people just type the permission bits directly. This would be 0444. Adjust to taste.

Setting Immutable Flag using ioctl() in C

I have attempted to make a script that creates a file and then sets it as immutable similar to the chattr +i command for linux. The script compiles (with gcc), runs and the file is created. However the file itself is not immutable and can be removed with a simple rm -f. I have attempted to stacktrace where chattr is called and I found a function called ioctl. I then used what little information I could gather and came up with what I have below. I narrowed it down from ext2_fs.h but it just doesn't seem to work. I've clearly overlooked something.
Updates to previous entry: Compiles but returns -1 on ioctl() function. Bad address shown with perror().
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
int main()
{
FILE *fp;
char shovel[16] = "I have a shovel!";
fp = fopen("/shovel.txt", "w+");
fwrite(shovel, sizeof(shovel[0]), sizeof(shovel)/sizeof(shovel[0]), fp);
ioctl(fileno(fp), FS_IOC_SETFLAGS, 0x00000010);
fclose(fp);
}
Any help appreciated.
You are using the right ioctl command, but you're passing it the wrong arguments.
The manpage for ioctl_list(2) shows that FS_IOC_SETFLAGS expects to receive a pointer to int (an int *), yet you're passing it an integer literal (hence the Bad Address error).
The fact that you don't to any error checking whatsoever is also not helping.
The correct flag to pass to FS_IOC_SETFLAGS is a pointer holding the value EXT2_IMMUTABLE_FL, which is defined in ext2fs/ext2_fs.h (some older / different Linux distributions seem to have it under linux/ext2_fs.h), so you'll need to #include <ext2fs/etx2_fs.h>. Make sure to install e2fslibs-dev (and probably you'll need linux-headers too).
This code is working:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
#include <ext2fs/ext2_fs.h>
int main()
{
FILE *fp;
char shovel[16] = "I have a shovel!";
if ((fp = fopen("shovel.txt", "w+")) == NULL) {
perror("fopen(3) error");
exit(EXIT_FAILURE);
}
fwrite(shovel, sizeof(shovel[0]), sizeof(shovel)/sizeof(shovel[0]), fp);
int val = EXT2_IMMUTABLE_FL;
if (ioctl(fileno(fp), FS_IOC_SETFLAGS, &val) < 0)
perror("ioctl(2) error");
fclose(fp);
return 0;
}
Remember to run this as root.
UPDATE:
As Giuseppe Guerrini suggests in his answer, you might want to use FS_IMMUTABLE_FL instead, and you won't need to include ext2_fs.h:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
int main()
{
FILE *fp;
char shovel[16] = "I have a shovel!";
if ((fp = fopen("shovel.txt", "w+")) == NULL) {
perror("fopen(3) error");
exit(EXIT_FAILURE);
}
fwrite(shovel, sizeof(shovel[0]), sizeof(shovel)/sizeof(shovel[0]), fp);
int val = FS_IMMUTABLE_FL;
if (ioctl(fileno(fp), FS_IOC_SETFLAGS, &val) < 0)
perror("ioctl(2) error");
fclose(fp);
return 0;
}
The main problem is that the ioctl wants a pointer to the mask, not a direct constant. You have to define a int variable, store the mask (0x10) in it and pass its address as third argument of ioctl.
Also, I'd add some hints:
other programs to change attributes are used to use low-level I/O directly (open, close...). Also, the file is usually opened with O_RDONLY.
Use FS_IMMUTABLE_FL istead the raw constant.
Get the current attribute mask first (FS_IOC_SETFLAGS) and mask it with the new flag, so other settings are not lost by the service.

Call to fdopendir() corrupts file descriptor

I stumbled upon a problem in a program I was working on. The following reproduces my issue:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
int main(int argc, char *argv[])
{
int fd, ret_fd;
DIR *dirp;
fd = open("./", O_RDONLY);
#if 1
if ((dirp = fdopendir(fd)) == NULL) {
perror("dirp");
return 1;
}
closedir(dirp);
#endif
ret_fd = openat(fd, "Makefile", O_RDONLY);
if (ret_fd == -1) {
perror("ret_fd");
return 1;
}
return 0;
}
Basically, the call to openat(), which has been preceeded by fdopendir(), fails with: Bad file descriptor. However, this does not happen if fdopendir() is omitted.
I know that fdopendir() makes internal use of the file descriptor, but shouldn't it revert any changes to it after calling closedir()?
What can I do to prevent openat() from failing in this case?
The POSIX description of fdopendir() says:
Upon calling closedir() the file descriptor shall be closed.
So the descriptor is likely to be closed by the time you call openat().
And this is from a typical Linux man page for fdopendir():
After a successful call to fdopendir(), fd is used internally by the
implementation, and should not otherwise be used by the application.

How do I prevent a library to print to stdout (in Linux/C)?

I am using a library that prints all kind of crappy messages to stdout. I try to keep a clean output on my program, but that makes it impossible.
Any idea?
You can close() the stdout socket and then open a new socket to /dev/null (assuming pretty much anything but windows here).
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int newfd;
printf("good things come...\n");
close(1);
newfd = open("/dev/null", O_WRONLY);
if (newfd != 1) {
fprintf(stderr, "uh oh... we didn't duplicate the socket properly\n");
exit(1);
}
printf("...to those that wait()\n");
}
And then running this you get:
$ ./test
good things come...
Note the no final line from printf.
[but I agree with the comments: using libraries that show signs of bad-things is probably a bad-choice for other reasons beyond the first one you spot]

write() returns -1 when writing to I2C_SLAVE device

I've read through the Linux kernel documents on i2c and written a code to try to replicate the command i2cset -y 0 0x60 0x05 0xff
The code that I've written is here:
#include <stdio.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <stdint.h>
#include <string.h>
int main(){
int file;
file = open("/dev/i2c-0", O_RDWR);
if (file < 0) {
exit(1);
}
int addr = 0x60;
if(ioctl(file, I2C_SLAVE, addr) < 0){
exit(1);
}
__u8 reg = 0x05;
__u8 res;
__u8 data = 0xff;
int written = write(file, &reg, 1);
printf("write returned %d\n", written);
written = write(file, &data, 1);
printf("write returned %d\n", written);
}
When I compile and run this code I get:
write returned -1
write returned -1
I've tried to follow exactly what the docs tell me, my understanding is that the address is set first with the call to ioctl, then I need to write() the register and then the data that I want sent to the register.
I've also tried to use use SMbus, but I can't get my code to compile using this, it complains at the linking stage that it can't find the functions.
Have I made any mistakes in this code? I'm a beginner to i2c and don't have a lot of experience with c either.
EDIT: errno give the following message: Operation not supported. I am logged in as root on this machine though, so I don't think it can be a permissions thing, although I may be wrong.
The way I got around this problem was to use SMBus, in particular the functions i2c_smbus_write_byte_data and i2c_smbus_read_byte_data. I was able to use these functions to successfully read and write to the device.
I did have a little trouble finding these functions, I kept trying to download libraries using apt-get to install the appropriate header files. In the end I simply downloaded the files smbus.c and smbus.h.
Then the code I needed was:
#include <stdio.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include "smbus.h"
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
int main(){
int file;
file = open("/dev/i2c-0", O_RDWR);
if (file < 0) {
exit(1);
}
int addr = 0x60;
if(ioctl(file, I2C_SLAVE, addr) < 0){
exit(1);
}
__u8 reg = 0x05; /* Device register to access */
__s32 res;
res = i2c_smbus_write_byte_data(file, reg, 0xff);
close(file);
}
Then if I compile the smbus.c file: gcc -c smbus.c and myfile: gcc -c myfile.c, then link them: gcc smbus.o myfile.o -o myexe I get a working executable that runs my I2C command. Ofcourse, I have smbus.c and smbus.h in the same directory as myfile.c.
In C, you can check the content of the errno variable to get more details into what went wrong. It is automatically declared when including errno.h and you can get a more descriptive text by calling strerror(errno).
Have you checked that you had write access to /dev/i2c-0 ?

Resources