【问题标题】:C named pipe does not work with multiprocessC命名管道不适用于多进程
【发布时间】:2021-07-23 05:02:07
【问题描述】:

我想在父进程中创建一个命名管道,然后在子进程中向它写入一个字符串,最后在父进程中读取这个字符串。运行程序时,我没有收到提示,例如仍在等待子进程结束。为什么子进程没有完成?

当前输出:

预期输出:

(没有多进程创建的图片)

我的源代码:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>

int main() {
     int pipefd[2]; 
     pid_t cpid;    
     char szoveg[32];   
     int fd, ret;
     char buf[32];

     buf[0]=0;



     cpid = fork();
     if (cpid == -1) {
       perror("fork");
       exit(-1);
     }

     if (cpid == 0) {    
       printf("%d: Child process\n",getpid());
       
       strcpy(buf,"Some text \0");
       printf("%d:write to fifo: %s:%ld\n",getpid(),buf,strlen(buf));
       write(fd,buf,strlen(buf)); 

       exit(0);

     } else {
       printf("%d: Parent process\n",getpid());
       
            ret=mkfifo("FifoName",00666);   
        if (ret == -1) {
            perror("mkfifo()");
            exit(-1);
        }

        fd=open("FifoName",O_RDWR);
        if (fd == -1) {
            perror("open() error!");
            exit(-1);
        }


        wait(NULL);   
        ret=read(fd,buf,32); 
        printf("%d:read() Read %d bytes: %s\n",getpid(),ret,buf);

        close(fd);
        
        unlink("FifoName"); 


       exit(0);
     }
}

【问题讨论】:

  • fd 未初始化。 write(fd,...) 失败。您可能打算写入管道。

标签: c multiprocessing pipe named-pipes


【解决方案1】:

威廉·珀塞尔说得对。问题是缺少 fd=open("FifoName",O_RDWR);来自子进程的行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2016-05-09
    • 1970-01-01
    相关资源
    最近更新 更多