After this
fd = open("hexdump_dup", O_CREAT | O_TRUNC | O_WRONLY, 0755); // (line 8)
write(fd, "/usr/bin/hexdump $@;", 20);
you need to execute hexdump_dup
executable, for that you need to use either system()
or exec()
family function. For e.g
system("./hexdump_dup 1 2 3"); /* after creating binary file(hexdump_dup) & writing command into it, you need to run it, for that use system() or exec() */
This
fd = open("hexdump_dup", O_CREAT | O_TRUNC | O_WRONLY, 0755);
will create the hexdump_dup
binary if it doesn't exist before & if exists before it will truncate its content to 0
. You can refer the man page of open() , it says
int open(const char *pathname, int flags, mode_t mode);
The argument flags must include one of the following access
modes: O_RDONLY, O_WRONLY, or O_RDWR. These request opening
the file read-only, write-only, or read/write, respectively.
O_CREAT
If the file does not exist it will be created. The
owner (user ID) of the file is set to the effective
user ID of the process.
O_TRUNC
If the file already exists and is a regular file and
the open mode allows writing (i.e., is O_RDWR or
O_WRONLY) it will be truncated to length 0. If the
file is a FIFO or terminal device file, the O_TRUNC
flag is ignored.
Lastly this
write(fd, "/usr/bin/hexdump $@;", 20);
writes 20
bytes containing array of characters /usr/bin/hexdump $@;
in this case into a file where fd
points i.e it will put this into hexdump_dup
file.
Here $@
means when you execute hexdump_dup
like
./hexdump_dup 1 2 3
it will take all the parameters to be passed.
int open(const char *pathname, int flags, mode_t mode);
The first argument is the file name to be opened, the second argument is set of flags. In your case, you have usedO_CREAT O_TRUNC O_WRONLY
. First creates the file if the file does not exist. O_TRUNC - If the file already exists and is a regular file and the access mode allows writing (i.e., is O_RDWR or O_WRONLY) it will be truncated to length 0. If the file is a FIFO or terminal device file, the O_TRUNC flag is ignored. Otherwise, the effect of O_TRUNC is unspecified.write(fd, "/usr/bin/hexdump $@;", 20);
. If I had to guess; this writes to the newly created file, the binary source code of the system's hexdump command... Please correct me if I'm wrong. And what does$@
that do ? @Gunasekar$@
. The number 20 represents the number of bytes to be written.write(fd, "/usr/bin/hexdump $@;", 20);
writes"/usr/bin/hexdump $@;"
to the file given with the file descriptorfd
up to 20 bytes. You may have noticed that the string has 20 characters too (excluding the terminatingNULL
).$@
in the string refers to all parameters passed into a script. See stackoverflow.com/questions/9994295/… for more about it.