【发布时间】:2020-01-04 09:16:00
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
int main(int argc, char* argv[]) {
int rc = fork();
// if I uncomment this line, the output file's is "testtest" when program exits.
// int file = open("./output", O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
// Use this line, the output file contains the string "TESTTEST".
int file = open("./output", O_CREAT|O_WRONLY|O_TRUNC);
if (rc < 0) {
fprintf(stderr, "fork failed\n");
exit(1);
} else if (rc == 0) {
write(file, "testtest", 8);
close(file);
} else {
write(file, "TESTTEST", 8);
close(file);
int wc = waitpid(rc, NULL, 0);
}
return 0;
}
我写了一个小程序来练习Linux API,然后遇到一个看不懂的问题。
当我传递权限参数时,我只能在子进程中写入内容。但是当我切换到另一个打开的函数时,我只能在父进程中写入内容。
有人可以帮忙解释一下原因吗?我可以在输出文件中同时获得“TESTEST”和“testtest”吗?
【问题讨论】:
-
你有一个竞争条件。没有指定父母或孩子是否赢得比赛,可能是随机的。
-
什么是你的“许可参数”?
-
S_IRUSR|S_IWUSR
-
实际上是错误的副本。
-
O_CREAT要求您将第三个参数传递给open。