[英]How to give filenames to a parent procces using FIFO(in C)?
我有 2 個進程,一個從輸入中讀取文件名,然后將該文件名提供給子進程。子進程確定給定文件退出的目錄,子進程將所有目錄名返回給父進程,然后父進程打印這些目錄名稱。我需要使用 FIFO(命名管道)來執行此操作。我卡在子進程為父進程提供目錄名稱的部分。有人可以幫忙嗎?
#include <stdio.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>
extern int errno;
#define FIFO "/tmp/fifo0002.1"
//searches for the direrctories
void listdir( const char *dir, const char *filename)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
char *subdir;
if((dp = opendir(dir)) == NULL)
{
fprintf(stderr,"cannot open directory: %s\n", dir);
return;
}
while((entry = readdir(dp)) != NULL)
{
if(lstat(entry->d_name, &statbuf) == 0)
{
if(statbuf.st_mode & S_IFDIR)
{
/* Found a directory, but ignore . and .. */
if(strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0)
continue;
// allocate space for parent directory, "/", subdir, plus NULL terminator
subdir = malloc(strlen(dir) + strlen(entry->d_name) + 2);
// Concatenate directory name
strcpy(subdir, dir);
strcat(subdir, "/");
strcat(subdir, entry->d_name);
/* Recurse at a new indent level */
listdir(subdir,filename);
free(subdir);
}
else
{
if(statbuf.st_mode & S_IFREG ){
if (strcmp(entry->d_name,filename)==0){
printf("%s\n",dir);}}
}
}
}
closedir(dp);
}
int main (void)
{ int r_fifo, w_fifo, r1_fifo, w1_fifo;
char filename[100];
printf("enter filename:");
scanf("%s",filename);
char buf[100];
char buf2[100];
pid_t pid;
if ((mkfifo (FIFO, S_IRUSR | S_IWUSR)) == -1) {
/* FIFO exists */
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 procces */
if ((r_fifo = open (FIFO, O_RDONLY)) < 0) {
perror ("open()");
exit (EXIT_FAILURE); }
write (w_fifo, filename, strlen (filename));
/*wait for child */
while (wait (NULL) != pid);
/*read from FIFO -> the directory names
read (r_fifo, buf, strlen (filename));
buf2[strlen(buf2)] = '\0';
printf(" directories:\n %s\n",buf2);*/
}
else {
/*child procces */
if ((w_fifo = open (FIFO, O_WRONLY)) < 0) {
perror ("open()");
exit (EXIT_FAILURE); }
/*Read from FIFO filename */
read (r_fifo, buf, strlen (buf));
buf[strlen(filename)] = '\0';
//printf("%s\n",buf);
listdir("/home/folder1",filename);
//close (w_fifo); /* EOF */
exit (EXIT_SUCCESS); }
return EXIT_SUCCESS;}
父進程打開 pipe 進行讀取並將描述符存儲在r_fifo
中。 然后它立即嘗試使用未初始化的w_fifo
描述符寫入pipe。
子進程相反,打開 pipe 進行寫入(分配給w_fifo
)然后嘗試使用未初始化的r_fifo
變量進行讀取。
父進程應該打開pipe進行寫,子進程應該打開讀。 兩者都需要使用正確和初始化的變量。
還有很多其他的問題,比如你在未初始化的arrays上使用strlen
function,不會得到arrays的大小。 在客戶端中,您讀入buf
但使用strlen(filename)
設置終止符。 而且您根本不會初始化filename
,並且仍然將其傳遞給listdir
function。
而且您確實需要檢查read
和write
返回的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.