天天看點

Linux命名管道FIFO實作程序間的檔案傳輸

設計兩個程式,要求用命名管道FIFO,實作程序間的檔案傳輸功能,即實作程序A将檔案file1的内容複制給程序B。file1是已經存在的檔案,file2可以不存在,如果存在就清空原來的内容。

接下來讓我們了解一下有名管道的使用.

Linux命名管道FIFO實作程式間的檔案傳輸

我們先以一個簡單的例子來熟悉FIFO的使用.

#include <unistd.h>

#include <stdlib.h>

#include <fcntl.h>

#include <limits.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <stdio.h>

#include <string.h>

int main()

{

    int pid;

    int fd;

    mkfifo("./named_pipe", 0777);

    pid = fork();

    if(pid > 0)

     {

      fd = open("./named_pipe", O_WRONLY);

      char buf[20] = "Hello world!";

      write(fd, buf, strlen(buf) + 1);

      close(fd); 

     }

    else if(pid == 0)

     {

      fd = open("./named_pipe", O_RDONLY);

      char buf2[20];

      read(fd, buf2, 1024);

      puts(buf2);

      close(fd);

     }

    return 0;

}

Linux命名管道FIFO實作程式間的檔案傳輸

上面的程式實作了父子程序間通過有名管道的通信,但有名管道的存在就是為了掙脫在無名管道通信中的程序親緣限制,是以接下來我們用兩個程式檔案來實作對無名管道的操作.

write.c:

#include <unistd.h>

#include <stdlib.h>

#include <fcntl.h>

#include <limits.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <stdio.h>

#include <string.h>

int main()

{

    int fd;

    char buf[20] = "I am Kevin.";

    mkfifo("./named_pipe", 0777);

    fd = open("./named_pipe", O_WRONLY);

    write(fd, buf, strlen(buf) + 1);

    close(fd);

    return 0;

}

read.c:

#include <unistd.h>

#include <stdlib.h>

#include <fcntl.h>

#include <limits.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <stdio.h>

#include <string.h>

int main()

{

    int fd;

    char buf[20];

    fd = open("./named_pipe", O_RDONLY);

    read(fd, buf, 1024);

    close(fd);

    puts(buf);

    return 0;

}

Linux命名管道FIFO實作程式間的檔案傳輸
Linux命名管道FIFO實作程式間的檔案傳輸

将執行順序改為先讀後寫,觀察輸出結果.

Linux命名管道FIFO實作程式間的檔案傳輸
Linux命名管道FIFO實作程式間的檔案傳輸

兩種執行結果向我們展示了有名管道的自帶阻塞功能,确實能為程式員對有名管道的讀寫操作帶來極大的便利.

接下來,我将以個人對題目的了解,來實作題目的要求.

程式設計思路大概是這樣的.先在目前目錄下建立檔案file,并向其寫入一定量的資訊;之後A程式建立FIFO,并将file檔案内的資訊讀出,送入FIFO中.之後,B程式讀FIFO中的資訊,并将資訊讀出到記憶體,再建立檔案file2,将這段資訊寫入file2.

A.c:

#include <unistd.h>

#include <stdlib.h>

#include <fcntl.h>

#include <limits.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <stdio.h>

#include <string.h>

int main()

{

    int fd;

    char s[150];

    mkfifo("./named_FIFO", 0777);

    FILE* fp = fopen("./file", "r");

    fgets(s, sizeof(s), fp);

    fclose(fp);

    fd = open("./named_FIFO", O_WRONLY);

    write(fd, s, strlen(s) + 1);

    close(fd);

    return 0;

}

B.c:

#include <unistd.h>

#include <stdlib.h>

#include <fcntl.h>

#include <limits.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <stdio.h>

#include <string.h>

int main()

{

    int fd;

    char s[150];

    fd = open("./named_FIFO",O_RDONLY);

    read(fd, s, 1024);

    close(fd);

    FILE* fp = fopen("./file2", "w+");

    fputs(s, fp);

    fclose(fp);

    return 0;

}

Linux命名管道FIFO實作程式間的檔案傳輸
Linux命名管道FIFO實作程式間的檔案傳輸
Linux命名管道FIFO實作程式間的檔案傳輸
Linux命名管道FIFO實作程式間的檔案傳輸

從上面的運作過程中,我們可以看到,程式要求的功能已得到實作.

繼續閱讀