簡體   English   中英

在C中使用命名管道

[英]Using named pipes in c

我有這個簡單的程序,它通過命名管道將值從子進程傳遞到父進程:

#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <fcntl.h>
 #include <sys/wait.h>
 #include <stdio.h>

int main()
{
 char * myfifo = "/home/tmp/myfifo";
   mkfifo(myfifo, 0666);
   int fd,rec;
   pid_t c=fork();

   if(c==0){
   fd = open(myfifo, O_WRONLY);
   rec=100;
   write(fd, rec, sizeof(rec));

   }
   if(c>0){
   sleep(1);
    fd = open(myfifo, O_RDONLY);
     read(fd, rec, sizeof(rec));
     printf("%d\n",fd);
     printf("%d\n",rec);

   }

}

這個程序打印fd = -1,而不是rec為100,而是打印rec的地址。我也嘗試將&rec放在讀寫中,但它沒有解決任何問題。我在做什么錯?

這條線有問題:

write(fd, rec, sizeof(rec));

這是write()的原型:

ssize_t write(int fd, const void *buf, size_t count);

這意味着,你從存儲在存儲器位置讀取rec ,沒有的內容rec

同樣的情況也適用於read() 您需要傳遞一個指向rec的指針,而不是rec本身。

另外,在打開文件並對其執行I / O操作后,請務必確保關閉文件。

這是您的代碼的正確副本:

#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdio.h>

int main()
{
   const char *myfifo = "/home/tmp/myfifo";
   mkfifo(myfifo, 0666);
   int fd, rec;
   pid_t c = fork();

   if(c == 0) {
       fd = open(myfifo, O_WRONLY);
       rec = 100;
       write(fd, &rec, sizeof(rec));
       close(fd);
   }
   if(c > 0) {
       sleep(1);
       fd = open(myfifo, O_RDONLY);
       read(fd, &rec, sizeof(rec));
       printf("%d\n", fd);
       printf("%d\n", rec);
       close(fd);
   }
}

當然,請始終確保您具有在該目錄中創建,讀取和寫入文件的適當權限。 另外,請確保目錄/home/tmp存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM