下面的 C 程序的预期行为是将其自己的可执行文件复制到一个新的随机命名的文件中,然后执行该文件,令人作呕。这应该会创建很多很多可执行文件的副本。这显然是一个糟糕的想法,但它仍然是我想要做的。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
int main(int argc, char* argv[]) {
/* Obtain name of current executable */
const char* binName = argv[0];
/* Print message */
printf("Hello from %s!\n", binName);
/* Create name of new executable */
char newBinName[] = "tmpXXXXXX";
mkstemp(newBinName);
/* Determine size of current executable */
struct stat st;
stat(binName, &st);
const int binSize = st.st_size;
/* Copy current executable to memory */
char* binData = (char*) malloc(sizeof(char) * binSize);
FILE* binFile = fopen(binName, "rb");
fread(binData, sizeof(char), binSize, binFile);
fclose(binFile);
/* Write executable in memory to new file */
binFile = fopen(newBinName, "wb");
fwrite(binData, sizeof(char), binSize, binFile);
fclose(binFile);
/* Make new file executable */
chmod(newBinName, S_IRUSR | S_IWUSR |S_IXUSR);
/* Run new file executable */
execve(
newBinName,
(char*[]) {
newBinName,
NULL
},
NULL);
/* If this code runs, then there has been an error. */
perror("execve");
return EXIT_FAILURE;
}
但是,输出如下:
Hello from ./execTest
execve: Text file busy
我认为文本文件“忙”,因为./execTest
仍在访问它......但我确实关闭了该文件的文件流。我做错了什么?