gpt4 book ai didi

子进程无法写入文件?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:52:59 24 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <errno.h>

int main() {
FILE *f = fopen("stories.txt", "w");


if (!f) {
error("Can't open stories.txt");
}

pid_t pid = fork();
if (pid == -1) {
error("Can't fork process");
}

if (!pid) {

fprintf(f, "f---- child process wrote\n");

printf("---- child process wrote\n");

if (execl("/bin/ls", "/bin/ls", NULL) == -1) {
error("Can't run script");
}

}

fprintf(stdout, "parent process wrote it after fork!\n");
fprintf(f, "parent process wrote it before return main!\n");
return 0;
}

当我在 Ubuntu Linux 64 位中运行上面的代码时,这

        fprintf(f, "f---- child process wrote\n");

没有写在stories.txt文件中。

你能帮我解释一下为什么会这样吗?

当我注释掉 execl 时,子进程对文件的写入就完成了。

最佳答案

在运行execl之前使用fclose(f);

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <errno.h>

int main() {
FILE *f = fopen("stories.txt", "w");


if (!f) {
error("Can't open stories.txt");
}

pid_t pid = fork();
if (pid == -1) {
error("Can't fork process");
}

if (!pid) {

fprintf(f, "f---- child process wrote\n");

printf("---- child process wrote\n");
fclose(f);
//--^^^^^^^^^^--//
if (execl("/bin/ls", "/bin/ls", NULL) == -1) {
error("Can't run script");
}


exit(0);
}

fprintf(stdout, "parent process wrote it after fork!\n");
fprintf(f, "parent process wrote it before return main!\n");
return 0;
}

关于子进程无法写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29339282/

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