0

In Linux both a binary executable file and a script can be marked "executable". I would like to determine in my gcc program whether the file is a script or a binary executable.

I read that there is an a.out.h file which allows to analyse the header of the file but I do not know how to use this in my code. Or if there is a simple solution instead.

3
  • man access will tell you if it's executable. Reading some number of bytes will tell if it's ascii or binary. man magic might be of interest too. Commented Nov 24, 2013 at 20:01
  • 1
    There's no such thing as a "gcc program". You may mean a "C program" that you compiled with GCC. Commented Nov 24, 2013 at 20:03
  • 1
    Consider whether you really need to do this. The whole point of scripts is that they can be executed as if they were binary executable programs. Commented Nov 24, 2013 at 20:28

1 Answer 1

5

You can check so-called magic bytes. For elf 1st four bytes are supposed to be 7f 45 4c 46 in hex. You have to care for byte order though.

Opening file in binary mode and reading 1st four bytes should suffice.

E.g.

shell$ hexdump -n 10 ./ni6_ga 0000000 457f 464c 0101 0301 0000 
Sign up to request clarification or add additional context in comments.

6 Comments

Whereas a script will start with #!
@JonathonReinhart: Not necessarily. An executable text file that doesn't start with #! is treated as a /bin/sh script. (Retroactively following up to your followup, it's certainly good practice to use the #! anyway.)
@KeithThompson Indeed. I forgot about that (as I think it is "good practice" to include the she-bang, regardless).
I usually write my shell scripts without #! and they run fine. So to check for that seems to be not reliable. The a.out.h file has a NMAGIC() macro to check the magic bytes. Has anyone used that yet? (And maybe has an example for that?)
The macros I mentioned refer to the older a.out executable format. For the common ELF format luk32's answer is correct and sufficient.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.