进程间通信有名管道(自创建自删除)

来源:互联网 发布:办公软件使用心得体会 编辑:程序博客网 时间:2024/05/18 02:57

这段时间学习进程间通信,给大家分享一下,这些理解即可,实际中用到会写的更复杂。先把代码贴出来

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <sys/types.h>#include <sys/stat.h>#include <errno.h>#include <fcntl.h>#include <unistd.h>int main(void){    char buf[128];    int a;    a = mkfifo("/test/6.28/f.fifo",0666);    printf("a=%d\n",a);    int fd=open("f.fifo",O_RDONLY);    read(fd,buf,sizeof(buf));    puts(buf);    close(fd);    unlink("/test/6.28/f.fifo");    return 0;}

这是读操作,头文件是我在vim编辑中默认的,有多余的头文件,不过没有关系。  mkfifo()是创建管道文件的函数,unlink()会删除参数pathname 指定的文件. 如果该文件名为最后连接点, 但有其他进程打开了此文件, 则在所有关于此文件的文件描述词皆关闭后才会删除. 如果参数pathname 为一符号连接, 则此连接会被删除。

<span style="color:#333333;">#include <fcntl.h>#include <unistd.h>int main(void){    char a[10];    int fd=open("f.fifo",O_WRONLY);    scanf("%s",a);    /*puts(a);*/    write(fd,a,6);    close(fd);    return 0;}</span>


这是写操作,编译好两个文件后,先执行read读操作,这是会阻塞到那里,然后执行write操作,输入字符串,通过管道传输过去。

0 0
原创粉丝点击