【发布时间】:2015-04-22 17:42:27
【问题描述】:
我有以下代码:
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h> // may not be needed
#include <sys/stat.h> // may not be needed
#include <stdlib.h>
#include <string.h>
typedef struct {
int pid;
char arg[100];
int nr;
} Str;
int main() {
int c2p[2];
pipe(c2p);
int f = fork();
if (f == 0) {
Str s;
s.pid = 1234;
strcpy(s.arg, "abcdef");
s.nr = 1;
close(c2p[0]);
write(c2p[1], &s, sizeof(Str));
close(c2p[1]);
exit(0);
}
wait(0);
close(c2p[1]);
Str s;
read(c2p[0], &s, sizeof(Str));
printf("pid: %d nr: %d arg: %s", s.pid, s.nr, s.arg);
close(c2p[0]);
return 0;
}
我不得不说到目前为止它工作得很好(pid、nr 和 arg 从未改变过),但是:
当子进程完成后,内存段(被子进程使用)是否被销毁(标记为空闲)? 如果是这样,在写入时间和读取时间之间是否存在丢失对该段的访问权或要更改的数据的风险?
(原来的问题是这样的:Sending structure through pipe without losing data)
【问题讨论】:
-
检查您正在进行的库调用的结果可能是值得的,因为相应地对这些结果采取行动。当子进程完成后,它的内存自然也就消失了。但不要假设管道上写入的数据也是如此。该管道仍然具有出色的读取句柄(和写入句柄,就此而言),因为您直到
wait()之后才关闭父进程的写入端)。