Это один из шагов набора упражнений, которые я делаю. Программа, которую я пишу, должна принимать более двух аргументов. Использование первого аргумента еще не реализовано. Остальные аргументы представляют собой список каталогов.Кошка с вилкой трубы execvp и dup2
На этом этапе мне нужно создать экземпляр cat для каждого каталога, заданного в аргументах, взять содержимое всех файлов каждого каталога, используя cat, и распечатать содержимое. Я должен уметь обрабатывать пути, такие как/home/directory и/home/directory/both (с последним/или без)
В настоящее время я пытаюсь запустить cat с аргументом/home/directory/* так что он будет читать все файлы в данном каталоге и возвращать их содержимое. Это мой код:
#include "Step1.h"
int main(int argc,char* argv[])
{
if(argc < 3)
{
printf("Usage: ./Step1 <exclusions file> <folder1> <folder2> <folder3> ...\n");
return -1;
}
int i;
for(i=2; i<argc; i++)
{
int catpipe[2];
if(pipe(catpipe))
{
printf("Error in pipe\n");
return -1;
}
pid_t pid = fork();
if(pid < 0)
{
printf("Error in fork\n");
return -1;
}
if(!pid)
{
dup2(catpipe[1],1); // cat pipe is used to get the output of cat program into this program.
close(catpipe[1]);
close(catpipe[0]);
char* args[3];
args[0] = "/bin/cat";
int length = strlen(argv[i]);
char* path;
if(argv[i][length - 1] != '/') // the path given does not have the ending/
{
path = malloc(length + 3);
strcpy(path,argv[i]);
path[length] = '/'; //append/at the end
path[length+1] = '*'; // append * at the end
path[length+2] = '\0';
}
else
{
path = malloc(length + 2); // the path contains the ending/
strcpy(path,argv[i]);
path[length] = '*'; // append * at the end
path[length+1] = '\0';
}
args[1] = path;
args[2] = NULL;
printf("%s\n",path);
execvp("/bin/cat",args);
}
close(catpipe[1]);
char buffer[200];
int total = read(catpipe[0],buffer,200); // read the output of cat program and print it.
buffer[total]='\0';
printf("The buffer contains: %s\n",buffer);
}
return 0;
}
Я побежал этот код следующим образом:
[email protected]:~/project$ ./Step1 exclusions ./testdirectory1 ./testdirectory2/
и результат я получил это:
/bin/cat: ./testdirectory1/*: No such file or directory
The buffer contains:
The buffer contains: ./testdirectory2/*
[email protected]:~/project$ /bin/cat: ./testdirectory2/*: No such file or directory
[email protected]:~/project$
но когда я делаю:
[email protected]:~/project$ /bin/cat ./testdirectory1/*
Результат:
Testline 1 of testfile1 in testdirectory1
Test line 1 of testfile1 in testdirectory1
Testline 1 of testfile2 in testdirectory1
Testline 1 of testfile3 in testdirectory1
Пожалуйста, помогите мне получить этот результат с моей программой.
Заранее спасибо
это потому, что при тестировании в оболочке, то '*' в ваших рассуждениях расширяется оболочки, в то время как, когда вы делаете вилку, то '*' интерпретируется как, просто файл с именем '*' – zmo
@zmo Разве не обойти это? – HZero
см. Мой ответ ;-) – zmo