c - C 中没有 fork 的无名管道

标签 c process pipe fork

我需要在 C 中创建无名管道而不使用 fork();

我有带 fork 的代码,但我找不到任何有关不带 fork 的无名管道的信息。我读到这是一个旧的解决方案,但它只是需要它。谁能帮我吗?

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define KOM "Message to parent\n"
int main()
{
    int potok_fd[2], count, status;
    char bufor[BUFSIZ];
    pipe(potok_fd);
    if (fork() == 0) {
        write(potok_fd[1], KOM, strlen(KOM));
        exit(0);
    }
    close(potok_fd[1]);
    while ((count = read(potok_fd[0], bufor, BUFSIZ)) > 0)
        write(1, bufor, count);
    wait(&status);
    return (status);
}

最佳答案

你应该更精确一点,你需要它做什么?仅在同一进程中向自己发送消息没有多大意义。

无论如何,您实际上可以不 fork 并在一个进程内完成所有操作,这并不是真正有用。

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#define KOM "Message to parent\n"
int main()
{
    int potok_fd[2], count;
    char bufor[BUFSIZ];
    pipe(potok_fd);
    write(potok_fd[1], KOM, strlen(KOM));
    fcntl(potok_fd[0], F_SETFL, O_NONBLOCK);
    while ((count = read(potok_fd[0], bufor, BUFSIZ)) > 0)
        write(1, bufor, count);
    return 0;
}

关于c - C 中没有 fork 的无名管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53033210/

相关文章:

C - 排序二维整数数组

c - printf 和++ 运算符

Rust:将标准输出写入缓冲区或字符串

java - 无法通过管道输出 Hadoop 命令

linux - 使用管道与子进程进行通信

c++ - 与使用早期版本的 Visual Studio 构建的第 3 方静态库链接时出错

c# - 等到多个命令行进程完成?

不同JVM之间的Java同步

node.js - Nodejs 和流管道

C - 指向结构体 "Segmentation fault (core dumped)"中的动态数组的指针