私がやろうとしているのは、lsコマンドの出力をファイルに入れ、grepコマンドを使用してそのファイルから読み取り、新しいファイルに保存し、そのファイルの内容に基づいて何かを出力することですターミナル。
したがって、次の出力リダイレクトがあります。
1) 標準出力から oioioi.txt というファイルへ (ls コマンドの場合)
2) oioioi.txt から grep.txt へ (grep コマンドの場合)
3) grep.txt からターミナルに戻る
これが私のコードです:
#include<stdio.h>
#include<sys/wait.h>
#include<unistd.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
//if(!fork())
//execl("/bin/grep","grep","input","oioioi.txt",0);
FILE *fp1,*fp2;
int fd,fd2;
fp1=fopen("oioioi.txt","w+");
fp2=fopen("grep.txt","w+");
fd=fileno(fp1);
fd2=fileno(fp2);
char filename[40],id[40],marks[40],filename2[40];
scanf("%s %s %s",filename,id,marks);
char *execarg2[]={"ls",0};
dup2(fd,1); //1st redirection
//close(1);
if(!fork())
{
execv("/bin/ls",execarg2);
}
sleep(1);
wait(NULL);
//dup(fd2);
close(fd);
dup(1);
dup2(fd2,1); //2nd redirection
if(!fork())
{
//sleep(1);
execl("/bin/grep","grep",filename,"oioioi.txt",0);
}
sleep(1);
wait(NULL);
close(fd2);
dup2(1,fd2); //3rd one which is the incorrect one
fscanf(fp2,"%s",filename2);
printf("%s",filename2);
if(strcmp(filename2,filename)==0)
printf("FILE FOUND");
return(0);
}
3番目は間違っていると思います。ただし、最初の 2 つについてもよくわかりません。皆さんが私のコードを見て、どこが間違っているかを教えてくれたり、次のリダイレクトに dup を使用した例を教えてくれたりしたら、本当に感謝しています.