'open() syscall sometimes fails and sometimes succeeds

I'm trying to understand why this is sometimes works, and sometimes doesn't - the open and read syscalls.

//open files   
fd1=open(argv[1],"O_RDONLY");
if(fd1==-1){
   printf("open file number 1 failed\n");
   exit(0);
} 
fd2=open(argv[2],"O_RDONLY");
if(fd2==-1){
    printf("open file number 2 failed\n");
    exit(0);
}

//read first byte
r1=read(fd1, &byte1, 1);
if(r1==-1){
    printf("read 1 1 error\n");
    close(fd1);
    exit(0);
}
r2=read(fd2, &byte2, 1);
if(r2==-1){
    printf("read 2 error\n");
    close(fd2);
    close(fd1);
    exit(0);
}

The output:

~/Desktop/os$ ./comp/out 1.txt 2.txt
open file number 1 failed
~/Desktop/os$ ./comp/out 1.txt 2.txt
read 1 1 error
~/Desktop/os$ ./comp/out 1.txt 2.txt
open file number 1 failed
~/Desktop/os$ ./comp/out 1.txt 2.txt
open file number 1 failed
~/Desktop/os$ ./comp/out 1.txt 2.txt
read 1 1 error
~/Desktop/os$ ./comp/out 1.txt 2.txt
read 1 1 error

Or as image: https://i.stack.imgur.com/NkvNC.png

c


Solution 1:[1]

"O_RDONLY"

Aaaaaaaaaaaaaaaaaaaaaaaaaa

You want

O_RDONLY




What's going on here is the second argument is a (mostly bitflags) number, and you're passing a string. Due to ASLR, the second argument is randomized so it works sometimes but not other times.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1