Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 没有子进程的命名管道_C_Named Pipes_Fifo - Fatal编程技术网

C 没有子进程的命名管道

C 没有子进程的命名管道,c,named-pipes,fifo,C,Named Pipes,Fifo,我使用FIFO编写了一个简单的读/写程序,用户的输入通过writer函数写入标准输出。但是问题是,我是否能够在不创建子进程的情况下运行这个程序(使用fork()操作)。从关于FIFO的示例中我看到,大多数具有命名管道/FIFO的读/写程序都是用两个文件完成的——一个用于读,一个用于写。我能把这些都归档吗 #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/

我使用FIFO编写了一个简单的读/写程序,用户的输入通过writer函数写入标准输出。但是问题是,我是否能够在不创建子进程的情况下运行这个程序(使用
fork()
操作)。从关于FIFO的示例中我看到,大多数具有命名管道/FIFO的读/写程序都是用两个文件完成的——一个用于读,一个用于写。我能把这些都归档吗

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

/* read from user  */
void reader(char *namedpipe) {
  char c;
  int fd;
  while (1) {
    /* Read from keyboard  */
    c = getchar();     
    fd = open(namedpipe, O_WRONLY); 
    write(fd, &c, 1);
    fflush(stdout); 
  }
}

/* writes to screen */
void writer(char *namedpipe) {
  char c;
  int fd;
  while (1) {
    fd = open(namedpipe, O_RDONLY);
    read(fd, &c, 1);
    putchar(c);
  }
}

int main(int argc, char *argv[]) {
  int child,res;            

  if (access("my_fifo", F_OK) == -1) {
    res = mkfifo("my_fifo", 0777);
    if (res < 0) {
    return errno;
    }
  }

    child = fork();       
    if (child == -1)      
      return errno;
    if (child == 0) {     
      reader("my_fifo");   
    }
    else {                
      writer("my_fifo");  
    }


  return 0;
}                      
#包括
#包括
#包括
#包括
#包括
#包括
/*从用户处读取*/
无效读取器(字符*命名管道){
字符c;
int-fd;
而(1){
/*从键盘读取*/
c=getchar();
fd=打开(仅命名管道,O_wr);
写入(fd和c,1);
fflush(stdout);
}
}
/*写入屏幕*/
无效写入程序(字符*命名管道){
字符c;
int-fd;
而(1){
fd=打开(仅命名管道);
读取(fd和c,1);
普查尔(c);
}
}
int main(int argc,char*argv[]){
int child,res;
如果(访问(“my_fifo”,F_OK)=-1){
res=mkfifo(“我的fifo”,0777);
如果(res<0){
返回errno;
}
}
child=fork();
如果(子项==-1)
返回errno;
如果(子项==0){
读卡器(“我的fifo”);
}
否则{
作家(“我的fifo”);
}
返回0;
}                      

您需要锁定文件,否则您可能会在其他人正在写入时尝试读取。您还需要刷新写入缓冲区,或者在内核写入缓冲区填满并写入文件之前,您对fifo的更改实际上可能不会被记录(在linux中,write并不保证写入会在该时刻发生。我看到您正在刷新标准输出,但您还应该在文件描述符上进行fsync。这将导致文件在任何写入操作期间锁定,以便其他人都无法写入。为了锁定文件以便读取,您可能必须使用信号量