gpt4 book ai didi

c - Quine 创建并执行文件

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:31 34 4
gpt4 key购买 nike

我正在创建一个 Quine在 C 中,我需要在其中创建一个新的 c 文件,然后编译并执行它。

我做了一个简单的片段来理解为什么它不起作用。

我的猜测是 execv 在 fprintf 完成写入之前启动命令,但我睡了一觉,它也没有工作。

(我为这个最丑陋的代码道歉,但这不是目标)

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main()
{
char *cmd[100]= {"sh", "-c", "\"gcc tmp.c && ./a.out\""};

fprintf(fopen("tmp.c", "w"), "#include <stdio.h>\nint main(){puts(\"Hello World\");}");
execv("/bin/sh", cmd);
return (0);
}

输出

sh: gcc tmp.c && ./a.out: No such file or directory

有什么想法吗?

最佳答案

您的参数数组 cmd 未以 NULL 指针终止。此外,它还有报价问题。

您还应该在 execv() 调用之前关闭文件。您在文件中看不到任何内容的原因是 fprintf() 缓冲。虽然所有打开的文件都在进程退出时关闭,但您在此之前正在执行。

int main(void)
{

char *cmd[]= {"sh", "-c", "gcc tmp.c && ./a.out", (char*)0};

FILE *fp = fopen("tmp.c", "w");
if (!fp) {
perror("fopen");
exit(1);
}

fprintf(fp, "#include <stdio.h>\nint main(){puts(\"Hello World\");}");
fclose(fp);
execv("/bin/sh", cmd);
perror("execv");
return (0);
}

关于c - Quine 创建并执行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40431832/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com