我有以下代码:
#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 从未改变),但是:
当子进程完成后,内存段(被子进程使用)是否被销毁(标记为空闲)? 如果是这样,是否存在在写入时间和读取时间之间丢失对该段的访问权限或要更改的数据的风险?
最佳答案
虽然子进程的内存在进程退出时返回给操作系统,但我怀疑这不是您真正要问的。
您可能更关心子进程退出后写入管道的数据会发生什么情况。正如 pipe(2) 手册页所述:
Data written to the write end of the pipe is buffered by the kernel until it is read from the read end of the pipe.
所以你的数据会到达,即使写入它的进程已经退出。
关于c - 通过管道发送变量时丢失数据的风险?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29805165/