[英]Child process cannot write to the file?
#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;
}
When I run the above code in Ubuntu Linux 64-bit, this 当我在Ubuntu Linux 64位上运行以上代码时,这
fprintf(f, "f---- child process wrote\n");
is not written in the stories.txt
file. 没有写在stories.txt
文件中。
Can you help me explain why this happens? 您能帮我解释一下为什么会这样吗?
When I comment out the execl
then the write to the file from the child process is done OK. 当我注释掉execl
,从子进程写入文件的操作就可以了。
use fclose(f);
使用fclose(f);
before run execl
在运行execl
之前
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.