微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C 命名管道不适用于多进程

如何解决C 命名管道不适用于多进程

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

当前输出

current output

预期输出

(没有多进程创建的图片

enter image description here

我的源代码

#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,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,32); 
        printf("%d:read() Read %d bytes: %s\n",ret,buf);

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


       exit(0);
     }
}

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。