【问题标题】:Risk of losing data when sending variables through pipe?通过管道发送变量时丢失数据的风险?
【发布时间】: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() 之后才关闭父进程的写入端)。

标签: c process pipe


【解决方案1】:

虽然子进程的内存在进程退出时归还给操作系统,但我怀疑这不是您真正要问的。

您可能更关心子进程退出后写入管道的数据会发生什么。正如 pipe(2) 手册页所述:

写入管道写入端的数据由内核缓冲 直到从管道的读取端读取。

因此,即使写入数据的进程已经退出,您的数据也会到达。

【讨论】:

  • 谢谢,这正是我要问的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-08
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 2015-05-10
  • 1970-01-01
相关资源
最近更新 更多