C 子进程无法写入文件?
未写入C 子进程无法写入文件?,c,linux,fork,C,Linux,Fork,未写入stories.txt文件中 你能帮我解释一下为什么会这样吗 当我注释掉execl时,从子进程写入文件的操作就完成了。使用fclose(f)运行前execl fprintf(f, "f---- child process wrote\n"); #包括 #包括 #包括 #包括 #包括 #包括 int main(){ 文件*f=fopen(“stories.txt”,“w”); 如果(!f){ 错误(“无法打开stories.txt”); } pid_t pid=fork()
stories.txt
文件中
你能帮我解释一下为什么会这样吗
当我注释掉execl
时,从子进程写入文件的操作就完成了。使用fclose(f)代码>运行前execl
fprintf(f, "f---- child process wrote\n");
#包括
#包括
#包括
#包括
#包括
#包括
int main(){
文件*f=fopen(“stories.txt”,“w”);
如果(!f){
错误(“无法打开stories.txt”);
}
pid_t pid=fork();
如果(pid==-1){
错误(“无法分叉进程”);
}
如果(!pid){
fprintf(f,“f----子进程写入\n”);
printf(“----子进程已写入\n”);
fclose(f);
//--^^^^^^^^^^--//
如果(execl(“/bin/ls”,“/bin/ls”,NULL)=-1){
错误(“无法运行脚本”);
}
出口(0);
}
fprintf(stdout,“父进程在fork之后编写!\n”);
fprintf(f,“父进程在返回main之前写入它!\n”);
返回0;
}
似乎execl接管了std描述符,因此子进程无法再使用它们。是的,但我在execlfprintf
缓冲之前使用了fprintf,并且您正在使用低级close()
关闭文件(实际上,由操作系统在execl()
上完成),因此缓冲区丢失。在执行前试着打电话给fclose(f)
。哦,你说得对,谢谢!!!!!!!!!!!!!!!!!函数的作用是:刷新流所指向的流(使用fflush(3)写入任何缓冲输出数据),并关闭底层文件描述符。
fprintf(f, "f---- child process wrote\n");
#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;
}