什么是对父进程的依赖
What is happing to the parent process?
这里的任务是:这是基本的C程序,必须包含两个进程。第一个在文件中写入 60 个随机数。需要写入的秒数必须读取文件,并且仅将偶数写入另一个新文件。所以我有这段代码和需要将偶数写入文件的父进程,它无法正常工作。我的问题是关于代码的结构。这是描述过程的最佳方式吗?
#include <stdio.h>
#include <fcntl.h>
int main() {
int pid, fd, buf, i, fd2, buf2;
pid = fork();
switch (pid) {
case 0: {
printf("n Child process is writing numbers. n");
fd = open("file.dat", O_RDWR | O_CREAT, 0644);
for (i = 0; i < 60; i++) {
buf = rand() % 20 - 10;
printf("n Writing number %d %d ", i + 1, buf);
write(fd, &buf, sizeof(buf));
}
close(fd);
break;
}
case -1: {
printf("n Fork error! n");
}
default: {
wait(pid);
printf("n Parent process is Copying numbers. n");
fd = open("file.dat", O_RDONLY);
fd2 = open("file_output.dat", O_RDWR | O_CREAT, 0644);
while (read(fd, &buf, sizeof(buf)) == sizeof(buf)) {
if (buf & ~1)
(buf2 = buf);
write(fd2, &buf2, sizeof(buf2));
printf("Writing number in file_output.dat %d n", buf2);
}
close(fd2);
close(fd);
}
}
return 0;
}
您的条件是错误的:
if (buf &~ 1) (buf2=buf);
write(fd2, &buf2, sizeof(buf2));
无论如何,您都会写出数字,但是如果它是奇数(除了您需要修复偶数/奇数测试),那么您不会更新buf2
。 如果第一个数字是奇数,则buf2
未初始化。
你需要这个:
if (buf % 2 != 0) continue;
write(fd2, &buf, sizeof(buf));
printf("Writing number in file_output.dat %d n", buf);
请注意,这可能无法正确测试负偶数。 您可以测试abs(buf) % 2 != 0
. 唯一可能无法处理的数字是 INT_MIN
。
你的偶数测试是错误的。您排除位 1,因此将选择任何大于 1 的数字。您可以有效地测试
if (buf & 0xfffffffe) ...
但是,您应该改为测试
if (!(buf & 1)) ...
甚至
if ((buf % 2) == 0) ...
好吧,代码中有几个错误。
看起来你想要实现这个目标:子级写入随机数,父级等待子级终止,读取随机数,只将偶数写出到第二个文件中。
但是,您使用了wait(),这是错误的函数。 而是像这样使用 waitpid():
waitpid(pid, NULL, 0);
另一个错误是只写入偶数的代码。我会这样写:
if (!(buf & 1))
write(fd2, &buf1, sizeof(buf1));
这样,您根本不需要 buf2。 实际上,在您当前的代码中,如果数字不均匀,它仍然会在文件中写入一个数字!它只会写入它再次读取的最后一个偶数。
为什么使用非便携式打开/读/写,而您可以使用便携式 fopen/fread/fwrite?这对我来说毫无意义。
让我们假设您的 int 大小 == 4。假设您的第一个进程写入 4 个字节,您的第二个进程出于某种原因将其读取为两个 2 字节的块,因此读取在您的循环中返回 2:while (read(fd, &buf, sizeof(buf)) == sizeof(buf))
2 == 大小 (buf)?不。也许您的循环在错误的条件下终止......
fread 使用两个参数解决了这个问题:一个用于项目的大小,另一个用于您想要的项目数。 for (size_t x = fread(&buf, sizeof buf, 1, file_ptr); x > 0; x = fread(&buf, sizeof buf, 1, file_ptr)) { /* ... */ }
......"成功完成后,fread() 应仅在遇到读取错误或文件末尾时才返回成功读取的元素数小于 nitems。"此保证不存在读取。您可能需要使用 x 来确定要写入的项目数,因为这会告诉您读取了多少项。
- 如何从C++中的依赖类型中获得它所依赖的类型
- boost::进程间消息队列引发错误
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 是否可以通过C++扩展强制多个python进程共享同一内存
- IPC使用多个管道和分支进程来运行Python程序
- 异常属于C++中的线程还是进程
- WMI检测进程创建事件-c++
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- 将依赖名称显式标记为类型名和模板的奇怪之处
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- C++GTKMM gui循环依赖关系
- c++多进程编写一个唯一的文件
- 通过ccmake在cmake中缓存依赖选项
- 如何在C++中将函数发送到另一个进程
- 在Qt Creator中,如何在连接到正在运行的进程后查看控制台输出
- 当基类是依赖类型时,这是一个缺陷吗
- 从不同的附加依赖项中识别等同命名的函数
- 如何在 CMake 中对目标依赖项进行分组?
- 在进程启动时加载依赖缓存
- 什么是对父进程的依赖