c - 使用命名管道的进程间通信

标签 c operating-system

我正在尝试编写一个简单的程序,将一个值从一个进程传递到另一个进程,而无需使用命名管道的父子属性。我写的代码:

#include <stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<signal.h>




int main(int argc, char **argv)
{   int fd,i,j;

    int * myfifo = "/tmp/myfifo";
    mkfifo(myfifo, 0666);

    pid_t c=fork();
    if(c==0){
    i=10;
    fd = open(myfifo, O_WRONLY);
    write(fd, &i, sizeof(i));
    printf("my pid is %d \n",getpid());
    }
    if(c>0){
    pid_t c2=fork();
    if(c2==0){
    fd = open(myfifo, O_RDONLY);
    read(fd, &j, sizeof(j));
    printf("passes value is %d",j);
    }
wait(0);
    }



}

我希望第一个 child 将 10 写入管道,第二个 child 从文件中读取并打印,这样我就可以知道它有效。这段代码给了我多个错误,尽管我无法理解。有什么想法吗?

我得到的错误:

In function ‘main’:|
warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]|
warning: implicit declaration of function ‘mkfifo’ [-Wimplicit-function-declaration]|
warning: implicit declaration of function ‘open’; did you mean ‘popen’? [-Wimplicit-function-declaration]|
]main.c|27|note: each undeclared identifier is reported only once for each function it appears in|
error:'O_WRONLY' undeclared(first use in this function)
error:'O_RDONLY' undeclared(first use in this function)

最佳答案

您没有包含正确的 header 。

对于 mkfifo()你需要 sys/stat.h:

SYNOPSIS

#include <sys/stat.h>

int mkfifo(const char *path, mode_t mode);

open()你需要 sys/stat.hfcntl.h:

SYNOPSIS

[#include <sys/stat.h>
#include <fcntl.h>

int open(const char *path, int oflag, ...);

当您调用这些函数时,您还需要实际检查返回值 - 确实会失败。

关于c - 使用命名管道的进程间通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55919530/

相关文章:

c - 是否可以在预处理器期间检查之前(在头文件中)是否定义了结构?

c - 如何使用 printf 在 C 中打印括号?

C静态数组初始化和圈复杂度

c# - 如何禁用系统设备?

c - 虚拟地址系统上的进程地址空间

android - 如果应用程序是第一次从 App Manager 运行,为什么 Android 在按下 Home 按钮后不保留应用程序状态?

c - 如何编写一个可以同时采用动态/静态分配的二维数组的 c 函数?

c - postfix 评估器不工作

Android,我可以根据自己的喜好操作操作系统吗?

operating-system - Rust 调用失败::fail_bounds_check 启用无着陆垫标志