2013-05-20 53 views
1

我不明白我在做什麼錯誤,請幫助我指出。我只是在這裏給我輸入我正在嘗試的程序,以便它很容易理解。我創建了3個命名管道,並將字符串"Hello, world!"寫入第一個命名管道myfifo.example。現在我正在讀取相同的命名管道,並試圖將數據複製到第二個命名管道cmyfifo11。這種讀寫不是偶然發生的。它甚至不是印刷行(1)(2)。任何機構請糾正我。mkfifo讀取和寫入錯誤

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

int main() 
{ 
    int n, fd1, fd2; 
    int pid,status; 
    char line[30]="Hello, world!\n"; 
    if (mkfifo("myfifo.example", 0660)<0) 
     perror("Cannot create fifo"); 

    if (mkfifo("cmyfifo11", 0660)<0) 
     perror("Cannot create fifo1"); 
    if (mkfifo("cmyfifo22", 0660)<0) 
     perror("Cannot create fifo2"); 
    if((fd1= open("myfifo.example", O_RDWR))<0) 
     perror("Cannot open fifo to write"); 

    if ((pid = fork()) < 0) 
     perror("fork error"); 
    else if(pid==0){ 
     int z=write(fd1,line,strlen(line)); 
     printf("Write is done on myfifo.example\n"); 
     printf("CHILD PROCESS 1\n"); 
     fd2=open("cmyfifo11",O_RDWR); 
     printf("Value of fd2=%d\n",fd2); 
     if(fd2<0) 
      printf("Cannot open cmyfifo11\n"); 
     printf("Reading\n"); 
     if((n=read(fd1,line,z))<0) /* Read and write is not happening */ 
      perror("Read error"); 
     printf("Value of n:%d with line %s\n",n);--->(1) 
      int x=write(fd2,line,n);-------------->(2) 
      printf("%d\n",x); 

    } 

    else if(pid>0){ printf("Parent area with %d\n",getpid());sleep(300);} 
    printf("Common area\n"); 

    return 0; 
} 

輸出中是

Write is done on myfifo.example 
CHILD PROCESS 1 
Value of fd2=4 
Reading 
Parent area with 349 

回答

1

你有一個分割的錯,因爲你忘了傳遞lineprintf()

printf("Value of n:%d with line %s\n",n) 

應該

printf("Value of n:%d with line %s\n",n, line); 
+0

嘿感謝了很多阿爾珀,我正在挖掘是從早上起的事情,謝謝指出。現在工作正常。 – Poorvi