[英]How to use FIFO with dup2?
我有 2 個進程,一個從輸入中讀取文件名,然后將該文件名提供給子進程。子進程確定給定文件退出的目錄,子進程將所有目錄名返回給父進程,然后父進程打印這些目錄名稱。我需要使用 FIFO(命名管道)來執行此操作。我將文件名直接放入系統調用以檢查 FIFO 是否可以使用它,但它不起作用,我不知道該怎么做有人請幫忙嗎?
#include <stdio.h>
#include<fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <errno.h>
#include <dirent.h>
//#include <string.h>
extern int errno;
#define FIFO "/tmp/fifo0003.1"
#define FIFO2 "/tmp/fifo0004.1"
int main (void)
{
int r_fifo, w_fifo, r_fifo2, w_fifo2;
char filename[100];
printf("enter filename:");
scanf("%s",filename);
char buf[100];
char buf2[100];
int fd;
pid_t pid;
int stdoutCopy=dup(1);
if ((mkfifo (FIFO, S_IRUSR | S_IWUSR)) == -1) {
if(errno == EEXIST)
perror ("mkfifo()");
else {
perror("mkfifo()");
exit (EXIT_FAILURE);
} }
if ((mkfifo (FIFO2, S_IRUSR | S_IWUSR)) == -1) {
if(errno == EEXIST)
perror ("mkfifo()");
else {
perror("mkfifo()");
exit (EXIT_FAILURE);
} }
pid = fork ();
if (pid == -1)
{ perror ("fork()");
exit (EXIT_FAILURE);
}
else if (pid > 0) {
/*parent writes to fifo */
if ((w_fifo = open (FIFO, O_WRONLY)) < 0) {
perror ("open()");
exit (EXIT_FAILURE); }
write (w_fifo, filename, strlen (filename));
/*wait for child */
while (wait (NULL) != pid);
/*read FIFO2 */
if ((r_fifo2 = open (FIFO2, O_RDONLY)) < 0) {
perror ("open()");
exit (EXIT_FAILURE); }
//redo stdout
dup2(stdoutCopy,1);
close(stdoutCopy);
read(r_fifo2,buf,strlen(buf));
buf[strlen(buf)] = '\0';
printf("%s\n",buf);
else {
/*child procces */
if ((r_fifo = open (FIFO, O_RDONLY)) < 0) {
perror ("open()");
exit (EXIT_FAILURE); }
/*read FIFO */
read (r_fifo, filename, strlen (filename));
if ((w_fifo2 = open (FIFO2, O_WRONLY)) < 0) {
perror ("open()");
exit (EXIT_FAILURE); }
dup2(w_fifo2,1);
system("find -name file1>w_fifo2");
close(w_fifo2);
/* EOF */
exit (EXIT_SUCCESS);}
return EXIT_SUCCESS;}
外殼命令
find -name file1>w_fifo2
將標准 output 重定向到名為w_fifo2
的文件。
If you want the output of the command to be written to your pipe, represented by the w_fifo2
descriptor in your code, then you should duplicate it into STDOUT_FILENO
just like you do now, but not redirect output in the command you run:
find -name file1
另請記住,某些find
實現需要路徑作為第一個參數,否則命令將失敗:
find . -name file1
談到失敗,你真的應該檢查system
返回什么來檢查失敗。 如果你想讓 output 寫入標准錯誤(這是錯誤報告和輸出的正常通道),你還需要用你的 pipe 替換它:
dup2(w_fifo2, STDERR_FILENO);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.