c - 通过管道发送变量时丢失数据的风险?

标签 c process pipe

我有以下代码:

#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)

最佳答案

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

您可能更关心子进程退出后写入管道的数据会发生什么情况。正如 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/

相关文章:

c - 如何从字符串中读取未知数量的浮点值

c - C数组中最低有效字节在哪里

python - 如何使用已经运行的 blender 运行 python 脚本?

c - 声明 char 数组导致 execv() 不起作用

c - 图映射资源信号量

c - 如何获取和比较 libcurl 版本?

java.io.IOException : error=11 异常

远程计算机上的 C# 进程

shell - 我可以通过管道将文件从 find 传送到 less 吗?

c - 为什么要关闭 Linux 中的管道?